Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re^2: Assignment to a value only if it is defined

by voj (Acolyte)
on Jan 20, 2010 at 15:44 UTC ( #818488=note: print w/ replies, xml ) Need Help??


in reply to Re: Assignment to a value only if it is defined
in thread Assignment to a value only if it is defined

The "default" action is not to do a assignement at all. But using the current value of $foo will do it as JavaFan suggested:

$foo = $bar // $foo;

However this is not much better then

$foo = $bar if defined $bar;

Because the other part of the statement ($foo) is duplicated - if I have a long variable like $myhash{mykey}->{mykey2} instead of $foo it only gets uglier. I was looking for a simple and short syntax like:

$foo =// $bar

But appereantly such operator does not exist in Perl. The best solution I found so far (also ugly but not getting more complex if $foo and $bar are long expressions) is:

{local $_ = $bar; $foo = $_ if defined $_;}


Comment on Re^2: Assignment to a value only if it is defined
Select or Download Code
Re^3: Assignment to a value only if it is defined
by jdporter (Canon) on Jan 20, 2010 at 16:40 UTC
    Because the other part of the statement ($foo) is duplicated - if I have a long variable like $myhash{mykey}->{mykey2} instead of $foo it only gets uglier

    Then try:

    $_ = $bar // $_ for $myhash->{mykey}{mykey2};
Re^3: Assignment to a value only if it is defined
by ikegami (Pope) on Jan 20, 2010 at 19:02 UTC

    {local $_ = $bar; $foo = $_ if defined $_;}

    $foo = $_ for grep defined, expensive();

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (11)
As of 2014-08-29 14:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (280 votes), past polls