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

Sorry to bother you with a basic question, but I'm not getting this...I want to open up a file from STDIN and have this script edit it.
#!/usr/bin/perl -w print "File name to renumber:"; my $file = <STDIN>; open (FILE, "$file") || die $!; $|++; my $line = 0; while (<FILE>) { next if /^%/ ; s/^(?:N\d+\s?)?(?{$line++})/N$line / ; } continue { print FILE; close FILE; }
I know there is something lame that I'm not doing right but the perl basics on how to handle something so simple is bypassing my little brain....Thanks for any help!

Replies are listed 'Best First'.
Re: File Handle Basics
by fglock (Vicar) on Sep 03, 2002 at 23:20 UTC

    You are almost there. Just "print". Then output to whatever file you want using  yourscript.pl > outputfile.txt

    #!/usr/bin/perl -w print "File name to renumber:"; my $file = <STDIN>; open (FILE, "$file") || die $!; $|++; my $line = 0; while (<FILE>) { next if /^%/ ; s/^(?:N\d+\s?)?(?{$line++})/N$line / ; print; } close (FILE);

    You might also want to use these switches in your command line:

    -i[extension] edit <> files in place (makes backup if extension supplied) -n assume 'while (<>) { ... }' loop around program

    If you call your script with  perl -i -n all you need is:

    s/^(?:N\d+\s?)?(?{$line++})/N$line / unless /^%/;

    update: thanks Arien

      You want -p for the impicit loop and print, instead of -n wich just loops.

      Also, since I've picked up Golf recently...

      perl -i -lpe'/^%/?--$.:s/^(?:N\d+\s?)?/N$. /'

      — Arien

Re: File Handle Basics
by sauoq (Abbot) on Sep 04, 2002 at 00:54 UTC

    You are doing a couple things wrong here. As blaze mentioned, you'll need to chomp your input otherwise $file will have a "\n" on the end of it and that'll be assumed to be part of the filename by your open().

    You open the file for reading but then you attempt to print to it with your print FILE line. Not only will that fail because your file isn't open for writing, it wouldn't work as you might expect anyway because of the way you are mixing reads and writes. It would be better to write your results out to another file. Even when you use perl's -i flag or $^I variable, it writes the results out to a temporary file first.

    You are also closing the file in your continue block.

    -sauoq
    "My two cents aren't worth a dime.";
    
Re: File Handle Basics
by blaze (Friar) on Sep 04, 2002 at 00:22 UTC
    dont forget to chomp

    chomp(my $file = <STDIN>);