And the ever-popular:
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...


In reply to Re: Re: Get string for a word in a file after some specific pattern compare by jbert
in thread Get string for a word in a file after some specific pattern compare by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.