in reply to Variable assignment error checking

There are several ways. For example, instead of returning 0 on failure, throw an exception:
sub func { my $arg = shift; die 'Invalid Argument' if $arg > 10; return $arg - 2; } eval { $var = func($var) }; # No exception catching. print "$var.\n";

Another possibility might be to change the function to return two values: the result and success. Upon failure, the result would be the same as the input argument, but the success would be 0. Otherwise, the function would return the new result and 1:

sub func { my $arg = shift; return($arg, 0) if $arg > 10; return($arg - 2, 1); } my $var = 10; ($var, my $succ) = func($var); print "$var.\n";

Update: For numeric return values, you can just add a string to the number to indicate failure:

sub func { my $arg = shift; return $arg . 'E0' if $arg > 10; return $arg - 2; }

See Range Operators for a similar trick.

لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ

Replies are listed 'Best First'.
Re^2: Variable assignment error checking
by LanX (Saint) on Dec 15, 2013 at 06:59 UTC
    nice list, but why not changing the argument alias in place to only return the error code?

    DB<101> $var=2 => 2 DB<102> sub func { if ( $_[0] > 0 ) { $_[0]--; return OK_CODE; } return ERR_CODE; } DB<103> $err = func ($var); => "OK_CODE" DB<104> $err = func ($var); => "OK_CODE" DB<105> $err = func ($var); => "ERR_CODE"

    Cheers Rolf

    ( addicted to the Perl Programming Language)