Re: true false ? : expression thingy
- From: "Bigus" <someone@xxxxxxxxxxxxx>
- Date: Thu, 28 Jul 2005 12:36:25 +0100
"Anno Siegel" <anno4000@xxxxxxxxxxxxxxxxxxxxxxx> wrote in message
news:dcaenn$d40$1@xxxxxxxxxxxxxxxxxxxxxxxxxxxx
> Bigus <someone@xxxxxxxxxxxxx> wrote in comp.lang.perl.misc:
[..]>> my $incsubs;
>> $line =~ /\ts/i ? $incsubs = 0 : $incsubs = 1;
>>
[..]
> 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.
Ahhh, so this would work:
my $incsubs;
$line =~ /\ts/i ? ($incsubs = 0) : ($incsubs = 1);
> 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;
OK, that sounds good. I 'll use that in this case. The previous syntax would
be useful in situations where I want to make a non boolean assigment
resulting from a regexp match.
Thanks
Bigus
.
- References:
- true false ? : expression thingy
- From: Bigus
- Re: true false ? : expression thingy
- From: Anno Siegel
- true false ? : expression thingy
- Prev by Date: Re: true false ? : expression thingy
- Next by Date: Re: Problem with enqueuing/dequeuing objects between threads
- Previous by thread: Re: true false ? : expression thingy
- Index(es):