Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Append to beginning of line (multi line file)

by FireBird34 (Pilgrim)
on Jan 23, 2003 at 20:12 UTC ( [id://229412]=perlquestion: print w/replies, xml ) Need Help??

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

Just as a fun thing to do, I decided to make a command line program that will number each line in a file (don't ask why -- I just decided to do it ;)). So given the contents:

alpha
bravo
charlie
delta

The program would make that:

1. alpha
2. bravo
3. charlie
4. delta

The way I have it right now, the contents will turn into:

alpha
bravo
charlie
delta1. 2. 3. 4.

Can't seem to make the numbers append to the start of each file *lol*. So here is my code:
#!/usr/bin/perl use strict; #command line info my $usage = "$0 -file [file name]"; die "Usage: $usage \n"; if ((@ARGV == 0) || ((scalar @ARGV)%2 != 0)); my %CommandLine = @ARGV; my $file = $CommandLine(-file) || die "Usage: $Usage \n"; #end command line info print "Status: numbering each line in file \"$file\".\n"; &number; print "\nStatus: done numbering each line in file \"$file\".\n"; ## SUBROUTINE sub number { my $count; open(FILE, "$file") || die "Can't locate file \"$file\": $!"; my @file = <FILE>; # store contents of file into @file close FILE; open(FILE, ">>$file") || die "Can't locate file \"$file\": $!"; foreach my $line (@file) { (undef) = <FILE>; # stores number of lines into $. $count++; print FILE, "$count. "; if ($count == $.) { last; } } close FILE; }
Any suggestions on either making this code cleaner and/or making it work properly? (keep in mind that this was a trial and error thing on my part -- reading the lines in the file -- so I am unsure if there is a more effective way)

Also, I had to re-type this from the editor, as it isn't coppying properly -- if you see a typo, that is why.

Replies are listed 'Best First'.
•Re: Append to beginning of line (multi line file)
by merlyn (Sage) on Jan 23, 2003 at 20:17 UTC
Re: Append to beginning of line (multi line file)
by Enlil (Parson) on Jan 23, 2003 at 20:32 UTC
    one thing you can do for each line is just substitute the start of the line for the current number. as a one liner though:
    perl -pi.bak -e '$count++;s/^/$count. /' file_name
    or in your could you could change:
    foreach my $line (@file) { (undef) = <FILE>; # stores number of lines into $. $count++; print FILE, "$count. "; if ($count == $.) {last; } }
    to something like:
    foreach my $line (@file) { $count++; print FILE, "$count. $line"; }
    or:
    foreach (@file) { $count++; s/^/$count. /; print FILE; }
    As always TMTOWTDI. I am curious as to why this line:
    (undef) = <FILE>; # stores number of lines into $.
    and this line:
    if ($count == $.) {last; }
    is necessary.

    -enlil

      (undef)=<FILE>; reads lines out of <FILE>, and stores it nowhere, it's the same as <FILE>. The answer to your puzzle isn't that (undef)=<FILE> is somehow magical (other then having a list-context call that goes nowhere; ()=<FILE> would should work just as well for that), it's that $. is a special variable that holds the current (input) line number. It's updated on all reads.


      Warning: Unless otherwise stated, code is untested. Do not use without understanding. Code is posted in the hopes it is useful, but without warranty. All copyrights are relinquished into the public domain unless otherwise stated. I am not an angel. I am capable of error, and err on a fairly regular basis. If I made a mistake, please let me know (such as by replying to this node).

Re: Append to beginning of line (multi line file)
by krujos (Curate) on Jan 23, 2003 at 20:21 UTC
    You could just open and write the last one at the end. This should also fix your numbering problem.
    open(INPUTFILE, "$file"); open(OUTPUTFILE, ">$outputfile"); my $counter = 1; while (<INPUTFILE>) { print OUTPUTFILE "$counter. $_"; $counter++; } close(INPUTFILE); close(OUTPUTFILE);
    If you want to copy over the old file, just do it at the end.

    UPDATE: You should probably check to make sure the files actually open (using die) like you did in your original code.

    UPDATE2: Only now does command line register in krujos' head. Doh!
Re: Append to beginning of line (multi line file)
by castaway (Parson) on Jan 23, 2003 at 21:02 UTC
    Unless I'm much mistaken (which has been known to happen), you're opening the file, reading in the entire thing, closing it, opening it again for appending and writing "$count." to the file once for each line.
    As you're appending to the end of the file, thats why the line numbers appear at the end. I don't know (undef) = <FILE> but it doesn't seem to be springing to the beginning of the file, which is what you would need in order to write $count to the beginning.

    I suggest you try:
    1. Open file, read all lines, close file.
    2. Open another filename, write each $count and the line itself to the new file in a loop.
    3. Unlink the old file, rename the new one to the old.
    You can use @files to get the number of lines also, instead of reading the file again.

    C.

      Thanks for the input. The reasoning behind the (undef) = <FILE> area, was for a different program I was working on. It was reading through the file and printing out extra info I didn't want. So reading around, I found a small snippit, that after using, seemed to fix my problem. Will look at some of your above examples -- thanks again. (also, I knew some of my code was 'excess', which is why I added that line for suggestions on making it better :))

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://229412]
Approved by ChemBoy
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (3)
As of 2024-04-20 03:24 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found