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

To add a string to a perl source file after the shebang line, my book says to do
while (<>){ if (/^#!/){ $_ .= "Add this line.\n"; } }
However this doesn't work. Instead, it erases the whole file. It makes sense that it should wok though, but for some reason it doesn't. Any idea why? thanks

Replies are listed 'Best First'.
Re: To add a string to the content of a file
by GrandFather (Saint) on Nov 27, 2005 at 23:25 UTC

    If you run that on its own then I would expect you will get no output at all because you don't print anything anywhere inside the loop. Perhaps what you want is:

    while (<>){ if (/^#!/){ $_ .= "Add this line.\n"; } print; }

    DWIM is Perl's answer to Gödel
Re: To add a string to the content of a file
by johnnywang (Priest) on Nov 28, 2005 at 01:01 UTC
    or just do a one-liner:
    perl -i.orig -p -e 's/^(#!.+)$/$1Add this line/' file
      To expand a little bit, the -p flag tells perl to wrap the whole script inside a:
      whie (<>) { # ... your code print $_; }

      The -i.orig tells it to first rename the original input file to its old name followed by .orig, then run the script and put its output into a new file with the same name as the input file.

      I suspect the code snippet you started off with assumed you were running under perl -p.

Re: To add a string to the content of a file
by swampyankee (Parson) on Nov 28, 2005 at 01:26 UTC

    If you invoked the script in some manner similar to:

    myscript > myscript.pl

    The first thing that will happen is that the shell will erase the file (or move the end of file marker to the beginning of the file, which is kind of the same thing)

    Also, as noted by our beloved GrandFather and johnnywang your script isn't generating any output

    corrected homenode links

    emc