http://qs321.pair.com?node_id=1067195


in reply to Variable assignment error checking

I think changing the sub to return $var in event of it being unable to complete its intended purpose would be the best option.

I don't like it but if changing the sub can't be done then this is the most consice method I could think of.

use strict; use warnings; my $var = 'foo'; my $tmp; $var = ( $tmp = return_false() ) ? $tmp : $var; print "$var\n"; $var = ( $tmp = return_true() ) ? $tmp : $var; print "$var\n"; sub return_true { return 'bar'; } sub return_false { return; }

Replies are listed 'Best First'.
Re^2: Variable assignment error checking
by NetWallah (Canon) on Dec 15, 2013 at 01:51 UTC
    It is arguably more readable to save off the old value, and re-instate it if func returns undef/zero:
    my $oldval; $val = func( $oldval=$val) || $oldval;
    Newer perl's allow the alternative of using the // (defined or) operator.

    To maintain the challange of "not creating a new variable", one could try:

    $val = func( $_=$val) || $_;
    Add a BLOCK, if $_ is being abused:
    $val = do{ func( local $_=$val) || $_ };

                 When in doubt, mumble; when in trouble, delegate; when in charge, ponder. -- James H. Boren