Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked

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'

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://980663]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (5)
As of 2018-06-22 21:32 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (124 votes). Check out past polls.