Beefy Boxes and Bandwidth Generously Provided by pair Networks DiBona
Think about Loose Coupling
 
PerlMonks  

Re: ||= (poorly documented?)

by tobyink (Abbot)
on Jul 09, 2012 at 06:54 UTC ( #980663=note: print w/ replies, xml ) Need Help??


in reply to ||= (poorly documented?)

In general, where X is an existing operator, then:

$foo X= $bar; # is short for: $foo = $foo X $bar;

Practical examples:

$foo += $bar; # is short for: $foo = $foo + $bar; $foo ||= $bar; # is short for: $foo = $foo || $bar; $foo .= $bar; # is short for: $foo = $foo . $bar; $foo *= $bar; # is short for: $foo = $foo * $bar;

This convention originally comes from Algol 68, but was made popular by C/C++ and is also available in many other languages (Java, Ruby, Python, Javascript, PHP, etc).

I would suppose that the reason these aren't documented in detail in perlop would be that people are expected to be already familiar with the convention. The Perl documentation probably shouldn't assume familiarity with other programming languages, but (especially for the older parts of the manual) they often seem to.

By the way, what the code you originally posted does is this: it creates a file handle $FH by opening the file with IO::File, but uses a hash %OUTFH in order to cache the file handles, and avoid opening the same file twice.

A longer way of writing the same thing would be:

$OUTFH{$name} = $OUTFH{$name} || IO::File->new(">g:\\perl_scripts\\$na +me.log"); $FH = $OUTFH{$name} or die $!;

It's actually a fairly common construct. The poor man's memoization...

my $result = $cache{$input} ||= my_function($input);

... and probably ought to be documented in some of those lists of Perl idioms.

perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'


Comment on Re: ||= (poorly documented?)
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://980663]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (7)
As of 2014-04-18 08:12 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (464 votes), past polls