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;