Home > Archive > PERL Beginners > January 2007 > fishy conditional expression
You are viewing an archived Text-only version of the thread.
To view this thread in it's original format and/or if you want to reply to
this thread please [click here]
| Author |
fishy conditional expression
|
|
| Tom Arnall 2007-01-29, 6:58 pm |
| the following script:
if (@f = `cat nonExistentFile` ) {
print 1;
}
if (@f = `cat nonExistentFile` && (1==1)) {
print 2;
}
gets:
cat: nonExistentFile: No such file or directory
cat: nonExistentFile: No such file or directory
2
seems to me both print statements should be skipped. what am i missing?
tom arnall
north spit, ca
"Relax, the tests extend the compiler."
| |
| Jason Roth 2007-01-29, 6:58 pm |
| Hi Tom,
This is because of operator precedence, && is higher then =. What you
are effectively saying is
@f = (`cat nonExistentFile` && 1==1)
when you probably want
(@f = `cat nonExistentFile`) && 1==1
The code you have ends up assigning to @f an array with a single
element, the empty string. This then evaluates to true in the
conditional statement.
-Jason
On 1/28/07, tom arnall <kloro2006@gmail.com> wrote:
> the following script:
>
> if (@f = `cat nonExistentFile` ) {
> print 1;
> }
>
> if (@f = `cat nonExistentFile` && (1==1)) {
> print 2;
> }
>
> gets:
>
> cat: nonExistentFile: No such file or directory
> cat: nonExistentFile: No such file or directory
> 2
>
> seems to me both print statements should be skipped. what am i missing?
>
> tom arnall
> north spit, ca
>
>
> "Relax, the tests extend the compiler."
>
>
> --
> To unsubscribe, e-mail: beginners-unsubscribe@perl.org
> For additional commands, e-mail: beginners-help@perl.org
> http://learn.perl.org/
>
>
>
| |
| Paul Lalli 2007-01-29, 6:58 pm |
| On Jan 29, 12:13 am, kloro2...@gmail.com (Tom Arnall) wrote:
> the following script:
>
> if (@f = `cat nonExistentFile` ) {
> print 1;
> }
>
> if (@f = `cat nonExistentFile` && (1==1)) {
> print 2;
> }
>
> gets:
>
> cat: nonExistentFile: No such file or directory
> cat: nonExistentFile: No such file or directory
> 2
>
> seems to me both print statements should be skipped. what am i missing?
The fact that you changed the contexts. In the first, the backticks
are evaluated in a list context. They therefore return the empty
list. @f therefore contains the empty list. @f is then evaluated in
a boolean (ie, a scalar) context. An empty array in scalar context is
0, which is false, so the if block is skipped.
In the second, the backticks are part of the && conjunction. && takes
scalars on either side. So the backticks return the empty string.
The equality returns 1. ('' && 1) returns the false, represented as
the empty string. @f therefore contains one element, the empty
string. @f is then evaluated in a scalar context, and returns 1. 1
is true, so the if block is executed.
Hope that helps,
Paul Lalli
|
|
|
|
|