Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?

ranged conditional with variable

by Anonymous Monk
on Aug 22, 2006 at 00:01 UTC ( #568722=perlquestion: print w/replies, xml ) Need Help??

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 (Pope) on Aug 22, 2006 at 05:57 UTC
    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.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://568722]
Approved by GrandFather
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (7)
As of 2021-04-23 09:19 GMT
Find Nodes?
    Voting Booth?

    No recent polls found