Re: true false ? : expression thingy
- From: anno4000@xxxxxxxxxxxxxxxxxxxxxxx (Anno Siegel)
- Date: 28 Jul 2005 11:15:03 GMT
Bigus <someone@xxxxxxxxxxxxx> wrote in comp.lang.perl.misc:
> I'm not sure what this method is called, which is perhaps why I've had no
> luck when searching around the web for info on it, but when you want a
> 1-line alternative to an if...else.. construct, you can use the following
> syntax:
>
> $ctr > 3 ? $text = "yes" : $text = "no";
>
> that works fine, however, when I try this:
>
> my $incsubs;
> $line =~ /\ts/i ? $incsubs = 0 : $incsubs = 1;
>
> it doesn't work.. well, $incsubs equals 1 regardless whereas it works in the
> standard if...else.. construct.
>
> I guess this is because the regular expression doesn't return true/false, or
> sth like that.. is there a "trick" you can use to make this type of method
> work with regexps?
Wrong diagnosis. A regex returns a boolean value in scalar context,
that part of your expression is quite all right.
Your problem is one of precedence. Perl parses your expression like
this:
( ( $line =~ /\ts/i) ? ( $incsubs = 0) : $incsubs) = 1;
So if you have a match, $incsubs is set to 0 and $incsubs is returned.
If you don't have a match, $incsubs is not set to 0, but returned as is.
In either case what is returned is $incsubs, and 1 is assigned to it
unconditionally. Hence the result you see.
Generally, the "?:" construct (sometimes called "ternary conditional",
btw) should not be used for operations that have a side effect, like
the assignments you are doing. Use a normal if/else for that, even if
it's a bit longer.
Using "?:", your conditional assignment can be written:
my $incsubs = $line =~ /\ts/i ? 0 : 1;
Now the assignment is outside the "?:". But now it becomes apparent
that this is (almost) equivalent to
my $incsubs = $line !~ /\ts/i;
which is what I would use.
Anno
--
If you want to post a followup via groups.google.com, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers.
.
- Follow-Ups:
- Re: true false ? : expression thingy
- From: Bigus
- Re: true false ? : expression thingy
- References:
- true false ? : expression thingy
- From: Bigus
- true false ? : expression thingy
- Prev by Date: Re: tied hash
- Next by Date: Re: true false ? : expression thingy
- Previous by thread: true false ? : expression thingy
- Next by thread: Re: true false ? : expression thingy
- Index(es):