Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

String Match Use of $1 Uninitialized

by spickles (Scribe)
on Dec 16, 2009 at 19:29 UTC ( [id://813056]=perlquestion: print w/replies, xml ) Need Help??

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

Why does this work:
my $text = "mississippi"; $text =~ m/(i.*s)/; print $1 . "\n";
And this gives me the error: 'Use of uninitialized value $1 in print'?
my $line = "PID: AIR-LAP1142N-A-K9 , VID: V01, SN: FTX1332SC15"; $line =~ m/AIR-LAP1142N-A-K9/; print $1 . "\n";
Please understand that before anyone tells me to go RTFM, I already have, and I wouldn't be asking questions if I didn't need some help. Thanks!

Replies are listed 'Best First'.
Re: String Match Use of $1 Uninitialized
by jettero (Monsignor) on Dec 16, 2009 at 19:35 UTC
    You second regex doesn't have any ()s in it. The $1 is populated from the ()s. Rather than saying RTFM, I'll say R this part of TFM: extracting matches.

    -Paul

Re: String Match Use of $1 Uninitialized
by kennethk (Abbot) on Dec 16, 2009 at 19:36 UTC
    The issue is that you are not capturing any text from your regular expression in the second case, so that sets all the captured groups to undef. Which strings are captured is controlled by parentheses in your regular expression - see perlre, perlretut. For example, of you wanted to capture the letters 'AIR' from your string into the $1 buffer, you might use:

    my $line = "PID: AIR-LAP1142N-A-K9 , VID: V01, SN: FTX1332SC15"; $line =~ m/(AIR)-LAP1142N-A-K9/; print $1 . "\n";
      Gentlemen:

      Makes a lot of sense now. Thanks for that. The docs I was reading weren't from perlretut and didn't make the function of grouping apparent.

      Regards,
      Scott

        Putting stuff in $1 is called capturing. While parens also do grouping, it's usually done using (?: ... ). For example, /abc(?:def|ghi)/.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://813056]
Approved by BioLion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (4)
As of 2024-04-25 17:52 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found