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

Re: Assignment to a value only if it is defined

by ikegami (Patriarch)
on Jan 20, 2010 at 19:01 UTC ( [id://818536]=note: print w/replies, xml ) Need Help??


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

my $bar = expensive(); $foo = $bar if defined $bar;
if (defined(my $bar = expensive())) { $foo = $bar; }
$foo = $_ for grep defined, expensive();
sub assign_ifdef { $_[0] = $_[1] if defined($_[1]) } assign_ifdef($foo, expensive());

The preceeding solution is very similar to what you asked (=ifdef) and very simple (single op).

Bonus points if $foo can also be a list.

I'm not sure if you mean

my $bar = expensive(); ($i1, $i2) = $bar if defined $bar;
or
if (defined(my $bar = expensive()) { $_ = $bar for $i1, $i2; }

Update: Added second and third.

Replies are listed 'Best First'.
Re^2: Assignment to a value only if it is defined
by voj (Acolyte) on Jan 21, 2010 at 16:48 UTC

    Thanks! That perfectly fits to assign to a scalar:

    sub setifdef { $_[0] = $_[1] if defined($_[1]) } setifdef $foo, $bar;

    And in case of a list I'll use the (slightly less readable) 'for grep defined,' psuedo-inline operator. It only makes sense with list references (if you treat (undef) as valid list). Defined scalar values which are transformed to a list can also be handled:

    @list = @{$_} for grep defined, $listref_or_undef; @list = split(",",$_) for grep defined, $splitme_if_defined;

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others imbibing at the Monastery: (3)
As of 2024-04-20 01:55 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found