Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

What is this erroring out?

by yoda54 (Monk)
on Mar 16, 2010 at 07:56 UTC ( [id://828834]=perlquestion: print w/replies, xml ) Need Help??

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

Hey monks,

Please enlighten.

What am I doing wrong here? I'm trying to decompose a string but for some reason I get uninitialized values.

Thanks!

sub test { my $a = shift; $a =~ /(.)(.)(.)(..)(.+)/; return 0 if ($1 !~ /(a)/); return 0 if ($2 !~ /(d|p|t)/); return 0 if ($3 !~ /(a|h|r|s|t)/); return 0 if ($4 !~ /(aw|er|dd|cb|aa)/); }

Use of uninitialized value $2 in pattern match (m//) at

Replies are listed 'Best First'.
Re: What is this erroring out?
by Corion (Patriarch) on Mar 16, 2010 at 08:02 UTC

    Your second match overwrites the captured values from the first match. If you want to keep the values, you need to copy them. Also, you should always check whether your match succeeds before operating on values:

    sub test { my $a = shift; die "Malformed value '$a'" if ($a !~ /(.)(.)(.)(..)(.+)/); my ($first,$second,$third,$fourth) = ($1,$2,$3,$4); return 0 if ($first !~ /(a)/); return 0 if ($second !~ /(d|p|t)/); return 0 if ($third !~ /(a|h|r|s|t)/); return 0 if ($fourth !~ /(aw|er|dd|cb|aa)/); }

    Alternatively, you could mush the five regular expressions into one:

    sub test { my $a = shift; $a =~ /(a)(d|p|t)(a|h|r|s|t)(aw|er|dd|cb|aa)(.+)/; }

    You could optimize the regex further by using character classes, that is, writing [dpt] instead of d|p|t.

      Thank you!!!
Re: What is this erroring out?
by Hue-Bond (Priest) on Mar 16, 2010 at 08:03 UTC

    When the line return 0 if ($2 !~ /(d|p|t)/); is executed, $2 is undef because in the previous regex matching (the one in the line just above it!) has only one pair of parentheses. Use something like this (untested):

    sub test { my $a = shift; my ($first, $second, $third, $fourth, $fifth) = $a =~ /(.)(.)(.)(.. +)(.+)/; return 0 if ($first !~ /(a)/); return 0 if ($second !~ /(d|p|t)/); return 0 if ($third !~ /(a|h|r|s|t)/); return 0 if ($fourth !~ /(aw|er|dd|cb|aa)/); }

    --
     David Serrano
     (Please treat my english text just like Perl code, i.e. feel free to notify me of any syntax, grammar, style and/or spelling error. Thank you!).

      Thanks you!!

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others browsing the Monastery: (5)
As of 2024-04-16 17:50 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found