Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re: How would you shorten this regexp conditional?

by japhy (Canon)
on Jan 25, 2002 at 17:23 UTC ( #141491=note: print w/ replies, xml ) Need Help??


in reply to How would you shorten this regexp conditional?

I'd just use the ternary operator: my $color = $white =~ /princepawn/ ? 'w' : 'b';
If I was feeling rowdy, I might do: my $color = ('b','w')[$white =~ /princepawn/];

_____________________________________________________
Jeff[japhy]Pinyan: Perl, regex, and perl hacker.
s++=END;++y(;-P)}y js++=;shajsj<++y(p-q)}?print:??;


Comment on Re: How would you shorten this regexp conditional?
Select or Download Code
Re: Re: How would you shorten this regexp conditional?
by merlyn (Sage) on Jan 25, 2002 at 18:58 UTC
    my $color = ('b','w')[$white =~ /princepawn/];
    Beware.. I've been burned by code like that. In a list context (which the indicies of a suffix part is eval'ed in), that's an empty list return for false, not "0", so you end up with an empty list value, and $color is undef, not the first item! You need a scalar inside the brackets to get it right, as in:
    my $color = ('b','w')[scalar $white =~ /princepawn/];

    -- Randal L. Schwartz, Perl hacker

      Except that this is in scalar context because of the scalar assignment. Had I mistakenly written my($color) = ..., then I agree I would have been burned, and rightly so.

      _____________________________________________________
      Jeff[japhy]Pinyan: Perl, regex, and perl hacker.
      s++=END;++y(;-P)}y js++=;shajsj<++y(p-q)}?print:??;

        Egad! Since when did the context of the literal slice propogate down into the right side of the slice? This is news to me. It was not that way when I invented it in Perl 3. {sigh} It must've changed in Perl5, because I'm sure I got burned by this in Perl4.

        -- Randal L. Schwartz, Perl hacker


        On further investigation, it appears that wantarray is true inside the subscript, but some sort of DWIMmery is happening. Ick!

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://141491]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (8)
As of 2015-07-04 08:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (58 votes), past polls