views:

110

answers:

4

I think its more a charachters, anyway, I have a text file, consisted of something like that:

COMPANY NAME

    City

    Addresss,
     Address number

    Email 

    phone number

and so on... (it repeats itself, but with different data...), lets assume thing text is now in $strting variable.

I want to have an array (@row), for example:

$row[0] = "COMPANY NAME";
$row[1] = "City";
$row[2] = "Addresss,
              Address number";
$row[3] = "Email";
$row[4] = "phone number";

At first I though, well thats easily can be done with grep, something like that: 1) @rwo = grep (/^^$/, $string); No GO! 2) @row = grep (/\n/, $string);

still no go, tried also with split and such, still no go. any idea? thanks,

+5  A: 

The way I understand your question, you want to grab the items separated by at least one blank line. Although /\n{2,}/ would be correct in a literal sense (split on one or more newlines), I would suggest the regex below, because it will handle nearly blank lines (those containing only whitespace characters).

use strict;
use warnings;

my $str = 'COMPANY NAME

City

Addresss,
 Address number

Email 

phone number';

my @items = split /\n\s*\n/, $str;
FM
+1  A: 
use strict;
 use warnings;
 my $string = "COMPANY NAME

        City

        Addresss,
         Address number

        Email

        phone number";

    my @string_parts = split /\n\n+/, $string; 
    foreach my $test (@string_parts){
          print"$test\n";
    }

OUTPUT:

COMPANY NAME
City
Addresss,
Address number 
Email
phone number
Nikhil Jain
Doesn't work, OP wants Address and Address number in the same part.
M42
@M42: ok, right, I misread the question.
Nikhil Jain
@M42:Now it will work.Thanks for pointing out the problem.
Nikhil Jain
+6  A: 

FM has given an answer that works using split, but I wanted to point out that Perl makes this really easy if you're reading this data from a filehandle. All you need to do is to set the special variable $/ to an empty string. This puts Perl into "paragraph mode". In this mode each record returned by the file input operator will contain a paragraph of text rather than the usual line.

#!/usr/bin/perl

use strict;
use warnings;

use Data::Dumper;

local $/ = '';

my @row = <DATA>;

chomp @row;

print Dumper(\@row);

__DATA__
COMPANY NAME

City

Addresss,
 Address number

Email 

phone number

The output is:

$ ./addr 
$VAR1 = [
          'COMPANY NAME',
          'City',
          'Addresss,
 Address number',
          'Email ',
          'phone number'
        ];
davorg
Since you can open a scalar as a filehandle, it's pretty easy to apply this trick to any data. `open my $fh, '<', \$data;`
daotoad
A: 

grep cannot take a string as an argument.

This is why you need to split the string on the token that you're after (as FM shows).

While it isn't clear what you need this for, I would strongly recommend considering the Tie::File module:

Zaid