[Omaha.pm] Another || quickie

Miller, Scott L (Omaha Networks) Scott.L.Miller at hp.com
Fri Aug 19 14:20:30 PDT 2005


I don't think you came away with the correct understanding of what that
snippet of text was saying.

 

What it was trying to say was you need to be a little bit careful when
using the || operator in an assignment statement because the || binds
more tightly than the =

 

This allows things like  $a = $b || $c;  to mean $a = $b when $b is
something that evaluates to true, and $a = $c when $b evaluates to
false.  Which seems to be exactly what you're attempting to do in your
example below, so you're fine.

 

Where you might run into trouble is if you attempt to use || when doing
something like:

@array = split || die "nothing to split";

 

Because the || binds tighter than =, die will always be evaluated no
matter what might happen to exist in $_; split will do it's thing to $_,
and then the die will evaluate, halting your script.

 

In this case, you are trying to use || for flow control, not for
assignment.  In this case, you want to use the 'or' keyword because it
binds less tightly than '=' and then the die will only be evaluated if
the assignment results in nothing being assigned.

 

  DB<3> p $_

 

  DB<4> @array = split or die "nothing to split";

nothing to split at (eval
44)[/usr/local/lib/perl5/5.6.1/perl5db.pl:1522] line 2.

 

  DB<5> $_ = "this is a test";

 

  DB<6> @array = split or die "nothing to split";

 

  DB<7> p join " ", @array;

this is a test

 

-Scott

________________________________

From: omaha-pm-bounces at pm.org [mailto:omaha-pm-bounces at pm.org] On Behalf
Of Kenneth Thompson
Sent: Friday, August 19, 2005 12:57 PM
To: Perl Mongers of Omaha, Nebraska USA
Subject: Re: [Omaha.pm] Another || quickie

 

So if I understand this correctly:

 

This:

 

    if ($oWkS->{Cells}[$iR][0]) {

      if ($oWkS->{Cells}[$iR][0]->Value != "") {

        $myVar = ($oWkS->{Cells}[$iR][0]->Value)

      }

    }

 

Is the same as this:

 

    if (!$oWkS->{Cells}[$iR][0]) {}

    elsif {$oWkS->{Cells}[$iR][0]->Value == "") {}

    else {

       $myVar = ($oWkS->{Cells}[$iR][0]->Value);

    }

 

Which is shortcut(ed?) as this? :

 

    My $t = (!$oWkS->{Cells}[$iR][0];

    $myVar = ((!$t) || ($t->Value != "") || $t->Value);

 

 

Which appears to work. However, this article (http://tinyurl.com/a3pt7)
seems to say it's bad to do this for assignment and should only be used
for flow control. Do I need to be concerned?

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.pm.org/pipermail/omaha-pm/attachments/20050819/c237295f/attachment.html


More information about the Omaha-pm mailing list