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 t开发者_开发问答hats 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,
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'
];
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;
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
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:
精彩评论