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

Hello Monks,

I am attempting exercise 5 in chapter 9 in the Llama 4th ed. I asks you to determine if a copyright line has been added to each file that you feed to it on the command line. If there is no copyright it is supposed to add one, while at the same time creating a backup for safe keeping.

Instead the program obliterates the contents of BOTH file and backup. Can someone help me figure out why this is happening? Here is my solution to the problem: -----------------------------
#!/usr/bin/perl -w use strict; $^I = ".bak"; my %do_these; foreach (@ARGV) { $do_these{$_} = 1; } while (<>) { if (/^## Copyright/) { delete $do_these{$ARGV}; } } @ARGV = sort keys %do_these; while (<>) { if (/^#!/) { $_ .= "## Copyright (C) 2008 by C'est mois\n"; } print; }


Thanks!

Replies are listed 'Best First'.
Re: Prorgam obliterates contents of files
by merlyn (Sage) on Dec 28, 2008 at 17:21 UTC
    You set $^I before the first diamond loop, where you are really only wanting to read the data. Delay that setting until just before the second diamond loop, and all will be well.

    I tend to put $^I in a local() setting in the smallest possible scope, just to minimize the potential for damage.

      so this is what local is used for ? controlling the value of a variable in a particular scope ? what other uses does local have ?
      You'll probably want to check whether @ARGV is empty after you've re-created it or that second diamond loop will sit quietly waiting for something when nothing is coming, i.e. the program won't terminate when @ARGV is empty.