perl script - Needing help with code?

Mel

New member
I need help with the following script. Im stuck. I need to replace anywhere it says SYNTAX or INDEX with the appropriate code but Im not sure what is right. Any suggestions would be great. thanks

#!/usr/bin/perl -w

########################################
# Script name: linenum.pl
# Functionality: This script requires that the command line argument # be a file. The file will be opened and each statement will be output to
# stdout in the following format: # Input format: Line number : Program # statement
# e.g. 22 : if ( $readme -eq $base )
# Case #1: ./linenumber printnum.sh
#######################################

# Handles the enforcement of correct number of arguments
unless (SYNTAX){
print "error: incorrect number of arguments",
"\n",
"usage: linenum [filename]",
"\n";
exit 1;
}


# Opens file from argument
open(MY_FILE, "$ARGV[INDEX]") or die
"error: argument must be a file\n",
"usage: linenum [filename]\n$!\n";

# Checks if file is a directory
if (-SYNTAX "$ARGV[INDEX]"){
print "error: argument must be a file",
"\n",
"usage: linenum [filename]\n";
exit 1;
}

$COUNTER=1; # Used for printing line numbers

# Loop and writes lines from file
SYNTAX ($LINE=<MY_FILE>){
# Adds leading zeros for numbers 1 digit long
if ($COUNTER<10){
print "000";
}
# Adds leading zeros for numbers 2 digits long
if (($COUNTER>9) && ($COUNTER<100)){
print "00";
}
# Adds leading zeros for numbers 3 digits long
if (($COUNTER>99) && ($COUNTER<1000)){
print "0";
}
# Prints line number and line
print "$COUNTER: $LINE";
$COUNTER+=1;
}
exit 0;
 
for INDEX: @ARGV is an array of command line arguments. Since you only have 1, the filename, its going to be zero in all cases.

For SYNTAX:

To quote Larry Wall (an important guy if you program perl) "There's more then one way to do it." If your instructor is looking for a specific answer, these may not be it.

1: scalar (@ARGV) == 1 #make sure there is exactly one argument

2: d #-d file test is only true if testing a directory

3. while # while loop such as that will continue until the end of the file is reached and line is set to a null value (0 or empty string for perl).

Also, make sure you close the file handle at the end of the program. Leaving them open, while not necessarily harmful, is not a good practice to be in.
 
Back
Top