[Israel.pm] setting $!

Offer Kaye offer.kaye at gmail.com
Sun Jul 18 13:49:09 PDT 2004

On Sun, 18 Jul 2004 22:09:51 +0300 (IDT), Shlomo Yona wrote:
> Hello,
> I have a function foo() which returns some scalar $s.
> I'd like to be able to do something like this:
>         my $s = foo() or die "foo: $!";
> I'd like to  be able to assign my own string to $! to be
> used right after a return from foo()  in case an undefined
> value is returned.
> What's the way to do this?
> --
> Shlomo Yona

There is no way to do this - $! is a special variable, at most you can
set it to some number as explained in perlvar:
               If used as a string, yields the corresponding system
error string.  You can assign a
               number to $! to set errno if, for instance, you want
"$!" to return the string for
               error n, or you want to set the exit value for the
die() operator.  (Mnemonic: What
               just went bang?)

As a workaround, I would use my own global variable and set its value
in foo(), e.g.:
my $err_msg; # global scope

my $s = foo() or die "foo: $err_msg";
sub foo {
   #something wrong:
   $err_msg = "returned undefined val\n";

Offer Kaye

More information about the Perl mailing list