SPUG: declarations

Jason Lamport jason at strangelight.com
Sun Dec 31 21:31:00 CST 2000


At 2:17 AM +0000 1/1/01, Greg McCarroll wrote:
>
>anyway the neatest way to declare the defaults just before they are
>used is (imho),
>
>$in{'server'} ||= 'default.mydomain.com';
>my $server = $in{'server'};
>
>for more info about ||= do a search for ``orcish maneuver'' on your
>favourite search engine (or better still google ;-) )

Actually, when I looked up "orcish maneuver" it didn't really explain 
the ||= operator.  So, I'll do the honors:

$a ||= $b;

seems rather cryptic, until you remember two things.  First, that 
it's simply a shorthand for:

$a = ( $a || $b );

and second, that || is a short-circuit operator which simply returns 
the last evaluated operand, so the above is semantically equivalent 
to:

$a = ( $a ? $a : $b );

So

$a ||= $b;

is a clever way if assigning a value to $a if and only if $a does not 
*already* have a (boolean true) value;

In the above example, writing the initialization like this:

$in{'server'} ||= 'default.mydomain.com';

only makes sense if you think that $in{'server'} *might* already 
contain a value (which you don't want to clobber).  If you're certain 
that $in{'server'} starts out undef, then it would be (slightly) more 
efficient to write:

$in{'server'} = 'default.mydomain.com';

(And I'm guessing that if %in starts out undef, then it would be even 
more efficient to write:

%in = ( 'server', 'default.mydomain.com' );

but I'm not sure.)

And if you want $in{'server'} to become 'default.mydomain.com' 
*regardless* of what its initial value might be, then you DON'T want 
to use the ||= operator.

Hope this helps.

-jason

 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
     POST TO: spug-list at pm.org       PROBLEMS: owner-spug-list at pm.org
      Subscriptions; Email to majordomo at pm.org:  ACTION  LIST  EMAIL
  Replace ACTION by subscribe or unsubscribe, EMAIL by your Email-address
 For daily traffic, use spug-list for LIST ;  for weekly, spug-list-digest
  Seattle Perl Users Group (SPUG) Home Page: http://www.halcyon.com/spug/





More information about the spug-list mailing list