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.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.