How to cancel the output if $ ^ i = ". Bak" already exists?

In Perl, I iterate over files according to a common pattern:

$^I=".bak"; 

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

where $ ^ I will back up. However, I want to check if the backup file exists and cancel the script, if so, so the backup is not overwritten. It must be explicitly deleted.

The problem is that outside the while loop I cannot do this

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

because $ ARGV is not set to <>, and inside the while $ ARGV loop is already replaced.

So am I missing something or do I need to do it differently?

Thanks!

+3
source share
1 answer

Check @ARGV(this is that null <>reads a list of its file names) before entering the while loop that uses it. eg.

die "Backup file already exists.\n" if -e $ARGV[0] . $^I;
+3

Source: https://habr.com/ru/post/1721636/


All Articles