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

I'm using the following snippet to modify a (passwd-style) file:
{ local($ORS, $^I, @ARGV) = ('', '.bak', $passwd); while (<>) { if (s|($username:).*\n|$username:$pass\n|) { $foundit = 1; } print; } }
How can I make it die() if it can't open $passwd? Do I need to use open() or die() ?

Replies are listed 'Best First'.
Re: local @ARGV and die() (boo)
by boo_radley (Parson) on Sep 14, 2001 at 02:52 UTC
    both, assuming $passwd contains a path to a file of some sort. See perldoc -f open for an example.
Re: local @ARGV and die()
by runrig (Abbot) on Sep 14, 2001 at 02:53 UTC
    Well, you could set a SIG handler, or you might just shift @ARGV yourself and use 'open(...) or die...':
    { local @ARGV = 'not_a_file'; local $SIG{__WARN__} = sub { die shift }; # SIG{__WARN__} is now set INSIDE the while loop # also, so you might want to unset it locally there while (<>) { print "This won't print\n"; } print "This won't print either\n"; }
      Oh, that's pretty neat! Thanks. use Fatal looks good too, but I'm using 5.005_03 (Debian Potato).
Re: local @ARGV and die()
by Rhandom (Curate) on Sep 14, 2001 at 09:57 UTC
    You can make use of the wonderful Fatal module. Try the following (assuming nonexistant doesn't exist).

    perl -e 'use Fatal qw(open); local @ARGV=qw(nonexistant); eval{ <> }; + print "$@\n";'
    So, all you need to do is put use Fatal qw(open); at the top of your script.

    my @a=qw(random brilliant braindead); print $a[rand(@a)];
(tye)Re: local @ARGV and die()
by tye (Sage) on Sep 14, 2001 at 19:29 UTC

    Using <> when @ARGV refers to a file that doesn't exist will die (Update: Nope, sorry, my testing was flawed; it just warns as is clearly implied elsewhere in this thread -- thanks to runrig for clueing me in).

    But local @ARGV isn't enough. You also need to reset $ARGV and the ARGV file handle. On Perl 5.6 and later,

    local(*ARGV); @ARGV= ($passwd);
    appears to work pretty well. Prior to 5.6, this fails in different ways depending on the version of Perl.

            - tye (but my friends call me "Tye")