neo1491 has asked for the wisdom of the Perl Monks concerning the following question:

Looking for the best way to exit out of a script if a specific scalar is undefined.

Example:
$foo_path = ('/mnt/foo') if ($^O eq "linux"); $foo_path = ('\\\C:\foo.exe') if (($^O =~ /mswin32|nt/i));
I want to be able to write something like:
if undef ($foo_path) { print "\nFOO was not intended to run on OS:$^0\n" exit; }
... but using undef in this way doesn't work. I've googled
"undef" but am still a bit confused. What's the best way
to verify if a scalar has been initialized and exit the script if it hasn't?
Thanks.

Replies are listed 'Best First'.
Re: Using UNDEF
by pc88mxer (Vicar) on May 22, 2008 at 16:46 UTC
    Use defined:
    die "FOO was not intended to run on OS $^O\n" unless defined($foo_path);
    Update: In 5.10 you can write:
    given ($^O) { when (/linux/) { $file_path = '/mnt/foo' } when (/mswin32|nt/) { $file_path = '\\\C:\foo.exe' } default { die "FOO was not intended..." } }
    You might even be able to factor the assignment to $file_path to outside the given statement -- gotta get 5.10 installed and try it out.
      Thanks pc88mxer... the 'unless defined' statement works great.
Re: Using UNDEF
by ikegami (Patriarch) on May 22, 2008 at 16:55 UTC

    Close.

    if (!defined $foo_path) { print "\nFOO was not intended to run on OS:$^0\n" exit; }

    Or even better

    if (!defined $foo_path) { die "\nFOO was not intended to run on OS:$^0\n" }

    Ref: defined, die

    Update: Fixed stupid mistake pointed out in MidLifeXis's reply.
    Update: Sigh! Fixed the second snippet too.

      Almost - the if should be negated :).

      if (! defined $foo_path) {...}

      --MidLifeXis

      Um... both ifs.