in reply to Write to multiple files according to multiple regex

This code is untested, but maybe it already works

# 1. elide manually managed count variable # 2. read current line into an actual variable while(my $line = <$fh_bigfile>) { # 3. let perl manage the count variable for my $i (0..$#inputs) { # 4. wrong sigil, use $...[$i] instead of @...[$i] # 5. explicitely refer to the line to print it # 6. enclose file handle in braces to make it more obvious print {$filehandles[$i]} $line if (/$regex[$i]/../^END_OF_BLOCK/); } }

The most important changes are 2., 4. and 5.

Replies are listed 'Best First'.
Re^2: Write to multiple files according to multiple regex
by Foodeywo (Novice) on Jul 21, 2015 at 12:02 UTC

    Thanks! Refering explicitly to $line is the key it seems, since within foreach, print refers to the elements of @inputs by default.

    I also added $line=~ to make it work. Curly braces (# 6.) where also neccessary.

    Now it writes all matches, but it puts all matches into the last filehandler only, throwing

    "Use of uninitialized value $_ in pattern match (m//) at parser.pl line 60, <> line 4401."

    for every line

      The conditional to print looked rather fishy, but I forgot about it. Try:

      print {$filehandles[$i]} $line - if (/$regex[$i]/../^END_OF_BLOCK/); + if ($line =~ /$regex[$i]/../^END_OF_BLOCK/);

      or did you already do exactly that? Please show your updated code.

        yes I added the $line=~
        print {$filehandles[$i]} $line if $line =~ /$regex[$i]/;
        I dropped the ../^END/ to play with the $/ operator. Not working yet though. Before that I had
        print {$filehandles[$i]} $line if ($line =~ /$regex[$i]/../^END/);
        which redundantly wrote all (correct) lines to the last (not the correct) filehandler.