in reply to Re: Get string for a word in a file after some specific pattern compare
in thread Get string for a word in a file after some specific pattern compare
my $word; { # Memory is cheap...for some applications local $/ = undef; open( FILE, "< $file" ) or die( "Ack: $!" ); my $whole_file = <FILE>; close FILE; # Assume whitespace delimiting ( $word ) = $whole_file =~ /TARGET\s*=\s*(\S+)/; } # $word is now set to our value or undefined
This slurps the entire file into memory and so isn't generally a good idea, but a variant of this approach *is* useful for more complex multi-line patterns. Particularly when you can use $/ = '\n\n'; or similar instead of $/ = undef; This can make many parsing jobs easier.
Basically, if you find yourself trying to keep state when parsing a multi-line expression, always consider changing the definition of '$/', it is a very powerful tool.
For those unfamiliar with this, evaluating <FOO> in a scalar context reads one 'line' from the filehandle FOO.
The definition of the end of a line is defined by the pattern held in the '$/' variable. You can set this to whatever you want to define your own line-endings.
Note bene: Don't use this to hack around DOS/Unix line ending conventions (CRLF versus LF). If you have problems with this look at the 'binmode' function call.
Hmm....am I far enough off-topic yet? Time to stop this...
|
|---|