Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re: Printing line before matching expression

by uday_sagar (Scribe)
on Sep 11, 2013 at 09:28 UTC ( [id://1053435]=note: print w/replies, xml ) Need Help??


in reply to Printing line before matching expression

Hope you would be interested in this!

open (INPUT, $ARGV[0]) or die "I couldn't get at input text"; open (SAME_INPUT, $ARGV[0]) or die "I couldn't get at input text"; open (OUTPUT, '>outfile.txt') or die "Can't write to outfile: $!"; while ($line = <INPUT>) { if (( $line =~ /index_1/ ) and ($line =~ /6/)) { $index = $.-2; } } while ($line = <SAME_INPUT>) { if ($. == $index) { print OUTPUT $line; } }

Replies are listed 'Best First'.
Re^2: Printing line before matching expression
by Laurent_R (Canon) on Sep 11, 2013 at 11:48 UTC

    Although possibly not terribly efficient, I like the idea of using 2 file handlers, it makes the code quite simple. But I would change it to something like this:

    open my $INPUT, "<", $ARGV[0] or die "I couldn't get at input text"; open my $SAME_INPUT, "<", $ARGV[0] or die "I couldn't get at input tex +t"; my $offset = $ARGV[1]; my $line = <$INPUT> for (1..$offset); # discard the n first lines, can +'t do anything with them anyway while (<$INPUT>) { $line = <$SAME_INPUT>; print $line if /$regex/; }

    There is also the alternative of slurping the file into an array and walking through the array. Reading the minus $n line is then trivial.

      Yes, concept of offset is good! :-)

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1053435]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others browsing the Monastery: (4)
As of 2024-04-18 21:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found