Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: Assignment to a value only if it is defined

by jettero (Monsignor)
on Jan 20, 2010 at 12:01 UTC ( #818431=note: print w/ replies, xml ) Need Help??


in reply to Assignment to a value only if it is defined

If bar() is a complex function, then perhaps it should be the one returning the default value...

If that's not reasonable, then perhaps you need a default wrapper or something... Here's two ideas:

sub mybar { my $t = bar(); return "default" unless defined $t; return $t; } sub default { my $to_call = shift; my $default = shift; my $t = to_call->(@_); return $default unless defined $t; return $t; }

Or just do what the others said above (5.10+ only): $x = bar() // "default";

-Paul


Comment on Re: Assignment to a value only if it is defined
Select or Download Code
Re^2: Assignment to a value only if it is defined
by voj (Acolyte) on Jan 20, 2010 at 15:44 UTC

    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 $_;}
      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};

      {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://818431]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (6)
As of 2015-07-07 09:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (88 votes), past polls