
conditional operator "?:"
Hi everyone,
I'm trying to check a variable for validity. If positive, it will keep it's
value, if not, the variable will be emptied (or undefined, or assigned with
something else).
Here's what I have:
#################################
#!/usr/local/bin/perl -w
use strict;
my ($empty1, $empty2);
my $test = "it contains |";
my $empty = ( ($test =~ /\|+/) ? $test : "" );
my $test1 = "it contains |";
($test1 =~ /\|+/) ? $empty1 = $test : undef $empty1;
my $test2 = "it contains |";
($test2 =~ /\|+/) ? $empty2 = $test : $empty2 = "it doesn't contain |";
print "$empty, $empty1, $empty2\n";
#################################
It prints: "it contains |, it contains |, it doesn't contain |"
The first two tests did work ok.
I just don't understand why the third test doesn't work as expected.
I looked for "perldoc -q operators" and found out:
Although it has the same precedence as in C, Perl's "?:"
operator produces an lvalue. This assigns $x to either $a
or $b, depending on the trueness of $maybe:
($maybe ? $a : $b) = $x;
But it doesn't talk about the way I did it for the second and third test.
Christian