Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: Regular Expression tricky newline problem

by graff (Chancellor)
on Jan 03, 2006 at 03:50 UTC ( #520491=note: print w/ replies, xml ) Need Help??


in reply to Regular Expression tricky newline problem

You've got answers for doing the appropriate regex on the slurped file data, as well as suggestions on improving how you do the slurp, so I'd just like to add that I wouldn't use a whole-file slurp into a scalar in a case like this.

The task appears to be line-oriented, so it would make sense to stick with line-oriented handling of the data. Depending on what else might need to be done with the file contents in the same script (whether you need to do things with other lines besides "Line 3"), you could either read the whole file into an array of lines and use grep on the array, or else use grep directly on the line-oriented file-read operator:

# load file into an array of lines, and use "Line 3": my @lines = <FILE>; my ( $keeper ) = grep /^Line 3 : /, @lines; # or just get "Line 3" from the file, and skip the rest: #my ($keeper) = grep /^Line 3 : /, <FILE>; # (update: added parens around $keeper, as per Aristotle's correction) # either way, remove the unwanted content from the kept line: $keeper =~ s/Line 3 : //;


Comment on Re: Regular Expression tricky newline problem
Download Code
Reaped: Re^2: Regular Expression tricky newline problem
by NodeReaper (Curate) on Jan 03, 2006 at 04:01 UTC
Re^2: Regular Expression tricky newline problem
by Aristotle (Chancellor) on Jan 03, 2006 at 13:16 UTC

    Careful, youíre invoking grep in scalar context. $keeper will only contain the count of matches. This has to be written with a parenthesised my, like so:

    my ( $keeper ) = grep /^Line 3 : /, @lines;

    However, that always goes through the entire data, regardless of where the match is found. A better way would be List::Utilís first; with which the context does not matter either:

    use List::Util qw( first ); my $keeper = first { /^Line 3 : / } @lines;

    Makeshifts last the longest.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (4)
As of 2014-09-20 01:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (151 votes), past polls