Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I'm attempting to do the following, be receive the following error: "Use of uninitialized value in pattern match (m//)"
foreach my $line (<FILE>) { if ($line =~ /PatternBegin/ .. /PatternEnd/) { $str .= $line; } }

If i remove the variable declaration and work from $_ with the following code everything works fine.
foreach (<FILE>) { if (/PatternBegin/ .. /PatternEnd/) { $str .= $_; } }

How do I make it work with the first example of code?

Replies are listed 'Best First'.
Re: ranged conditional with variable
by diotalevi (Canon) on Aug 22, 2006 at 00:04 UTC

    You thought the second match would use $line because the first did. It didn't. You didn't provide a target for /PatternEnd/ so it bound to $_. Write it using the second example I've quoted.

    # You wrote if ( $line =~ /PatternBegin/ .. $_ =~ /PatternEnd/ ) { # You wanted. if ( $line =~ /PatternBegin/ .. $line =~ /PatternEnd/ ) {

    ⠤⠤ ⠙⠊⠕⠞⠁⠇⠑⠧⠊

Re: ranged conditional with variable
by ikegami (Patriarch) on Aug 22, 2006 at 05:57 UTC
    Furthermore,
    foreach (<FILE>) {
    reads the whole file into memory, even though you only work on one line at a time. Use
    while (<FILE>)
    or (while (defined(my $line = <FILE>))) instead.
Re: ranged conditional with variable
by izut (Chaplain) on Aug 22, 2006 at 11:41 UTC

    I'm curious. What are you trying to do with that pattern matching? I've seen .. usage just in arrays, or iteration. Could you enlight me?

    Igor 'izut' Sutton
    your code, your rules.

      What you know is probably .. in list context. The OP is using .. in scalar context (the so called flip-flop operator), see perldoc perlop -> Range Operators

      -- Hofmator

        Thanks for your reply! We are always learning Perl magics :-)

        Igor 'izut' Sutton
        your code, your rules.