tags:

views:

56

answers:

1

In Perl, I'm looping over files using the common pattern:

$^I=".bak"; 

while(<>) {
  s/pattern/replacement/g;
  print;
}

where $^I will create backups. However, I want to test if the backup file exists and cancel the script if it does, so the back up isn't overwritten. It has to be explicitly removed.

The problem is that outside the while loop I can't do this

if (-e "$ARGV.bak") {
  # print warning and exit
}

because $ARGV isn't set until <>, and inside the while loop $ARGV has already been replaced.

So am I missing something or do I have to do this a different way?

Thanks!

+3  A: 

Check @ARGV (which is what null <> reads its list of file names from) before entering the while loop that uses it. e.g.

die "Backup file already exists.\n" if -e $ARGV[0] . $^I;
Michael Carman
Thx! That did it. :)
Keith Bentrup
If you're going to process more than one file, though, you should have a continue block that makes the same check for the next file on eof. And keeping track of "the next file" is not 100% trivial :)
hobbs
ephemient