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

Wise monks,

I have some functions that perform inplace edits on files passed as arguments. I set $^I to use <> "magic". They look like that:

sub inplace{ my @files = @_; local ($^I, @ARGV) = (".bak", $file); # Now i can use <> while(<>){ # do stuff on $_ print; } }
Now, I would like to check if all the files were successfully opened (like in open or die "$!"), but I can't find anything in the documentation that tells me how to do it. Is there anyway to do it without refusing to use $^I and <> "magic"?

Edited: Forgot local

Replies are listed 'Best First'.
Re: Checking status of implicit open (diamond operator)
by BrowserUk (Patriarch) on Mar 17, 2005 at 12:50 UTC

    Set a __WARN__ handler.

    >perl -i.bak -e"$SIG{__WARN__}=sub{ warn qq[failed:$ARGV]}; print <>" +fred.dat failed: fred.dat at -e line 1.

    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    Lingua non convalesco, consenesco et abolesco.
    Rule 1 has a caveat! -- Who broke the cabal?
      Thank's a lot for your reply! Was exactly what I need ++

      Now I have to make sure I'm not trapping the rest of the warnings, any guidance on where to search for info?

        You're localising $^I and @ARGV, localise $SIG{__WARN__} also:

        sub inplace{ my @files = @_; local($^I, @ARGV)=(".bak", $file); # Now i can use <> local $SIG{__WARN__} = sub{ ## Handle open errors here }; while(<>){ local $SIG{__WARN__}; # disable it for loop body # do stuff on $_ print; } }

        Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
        Lingua non convalesco, consenesco et abolesco.
        Rule 1 has a caveat! -- Who broke the cabal?
Re: Checking status of implicit open (diamond operator)
by Joost (Canon) on Mar 17, 2005 at 12:51 UTC
    AFAIK while(<>) already does that. Observe:
    > perl -nple1 non-existing Can't open non-existing: No such file or directory. > perl -nple1 unreadable.txt Can't open test.txt: Permission denied.
    update: actually, it appears to just skip processing the file (giving the warning), instead of abort, so you still need a SIG{__WARN__} or use warnings FATAL => all to catch it.