in reply to Match pattern per line and after another one as multiline in single file opening

my $data; open my $FH, '<' , $config or die "Cannot open $config: $!\n"; local $/ = undef; s/^\s*#.*\n|^\n//gm for $data = <$FH>; while ($data =~ m/\{([^}]*)\}/gx ) { print "$1\n"; } close $FH;

Since you did not provide a test file, it's untested...

  • Comment on Re: Match pattern per line and after another one as multiline in single file opening
  • Download Code

Replies are listed 'Best First'.
Re^2: Match pattern per line and after another one as multiline in single file opening
by kennethk (Abbot) on Feb 14, 2017 at 23:31 UTC
    TIMTOWDI, but I would suggest you replace:
    my $data; open my $FH, '<' , $config or die "Cannot open $config: $!\n"; local $/ = undef; s/^\s*#.*\n|^\n//gm for $data = <$FH>;
    with
    open my $FH, '<' , $config or die "Cannot open $config: $!\n"; local $/ = undef; my $data = <$FH>; $data =~ s/^\s*#.*\n|^\n//gm;
    The use of the for loop on a value you expect to be scalar confuses casual perusal, and you've declared the variable (my) at a different spot than where you initialize it. If you want to go compound, there's always
    (my $data = <$FH>) =~ s/^\s*#.*\n|^\n//gm;
    but that feels crowded to me. If I were actually writing this, I would do:
    my $data = do { local $/ = undef; open my $FH, '<' , $config or die "Cannot open $config: $!\n"; <$FH>; }; $data =~ s/^\s*#.*\n|^\n//gm;
    Slurping in a do loop keeps the filehandle tightly scoped and keeps that localization of the input file separator actually local. And note, even then, I personally prefer keeping the processing separate from the import.

    Update: Fixed typos; haukex++

    Update: Fixed typos; haukex++. Some days you just shouldn't post code.


    #11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.