On 3/7/07, Karyn Williams <[EMAIL PROTECTED]> wrote:

I have a script where I am trying to use the conditional operator.
Apparently I am confused as it always evaluates false.

        $initial ?
                $gecos = "$first $initial $last, $sid, SIR Fall 2007":
                $gecos = "$first $last, $sid, SIR Fall 2007";

It's a very confusing operator. One thing about it that's confusing is
its precedence: just higher than assignment. That means that your code
is really saying something like this:

   ($initial ? ($gecos = "fred") : $gecos)
     = "barney";

In other words, you're assigning the second string to $gecos in either
case (right on top of the first string, if $initial was true). If you
put in the needed parentheses, I think it would do what you expect,
even though it seems to be an odd programming style.

Are you using the return value from the conditional operator? If not,
you should code this as an ordinary if/else. But this isn't an
unreasonable use of this operator. I think what you really meant was
more like this, maybe?

   $gecos = $initial ?
     "$first $initial $last, $sid, SIR Fall 2007" :
     "$first $last, $sid, SIR Fall 2007";

I didn't have to use parentheses here for the same reason that your
code needed them: The precedence of ?: binds more tightly to its
arguments than = binds to its arguments.

Hope this helps!

--Tom Phoenix
Stonehenge Perl Training

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to