PYPL
PYPL

Reputation: 1849

perl regex for multi line file

I have strings like

     CASE: 8
     Location: smth
     Destination: 183, 3921,  2.293e-2, 729, 9
     END_CASE

I need to put number of CASE (8) and Destination parameters to variables... How to do that?

Upvotes: 1

Views: 111

Answers (1)

user1126070
user1126070

Reputation: 5069

Here is with regexp:

my $str = "CASE: 8
Location: smth
Destination: 183, 3921,  2.293e-2, 729, 9
END_CASE
        ";
my ($case,$dest) = $str= m!\A\s*CASE:\s*(\d+).+?Destination:\s*(.+?)\n!gis;
print "case: $case, dest: $dest\n";

EDIT:

If you would like to match multiline regexp, and your file is small you could slurp it.

If it is bigger then you could process it in chunks (blocks).

slurp:

local $/=undef;
open(my $fh,'<',...) or die $!;
my $str = <$fh>;
while ($str= m!\A\s*CASE:\s*(\d+).+?Destination:\s*(.+?)\n!is){
  print "case: $1, dest: $2\n";
}

process in chunks:

my $str;
while( my $line = <$fh>){
  if ($line !~ m!END_CASE!){
    $str .= $line;
  } else {
    $str .= $line;
    ### process $str
    my ($case,$dest) = $str= m!\A\s*CASE:\s*(\d+).+?Destination:\s*(.+?)\n!gis;
    print "case: $case, dest: $dest\n";
    ### reset chunk
    $str = '';      
  }
}

Regards,

Upvotes: 1

Related Questions