Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a Perl script that prints the contents of a file, prefixing each line with

ID: 3837945 • Letter: W

Question

Write a Perl script that prints the contents of a file, prefixing each line with a line number (show your code below).. The script must accept exactly 1 argument representing the name of the file.
The script must be able to handle the following error conditions:

Incorrect number of arguments and

The specified argument is not a file.

You cannot use the cat, wc, nor nl command in this assignment. You must use Perl to read the file and count the lines.

The printf function in Perl is useful for formatting numbers.

The script file name must be: linenum.pl.

The script permission must be 705.

Sample Output

Sunny Day Scenario:

csis345@csis345-vm:~$   perl linenum.pl /etc/updated.conf
0001: PRUNE_BIND_MOUNTS="yes"

0002: # PRUNENAMES=".git .bzr .hg .svn"

0003: PRUNEPATHS="/tmp /var/spool /media /home/.ecryptfs"

0004: PRUNEFS="NFS nfs nfs4 rpc_pipefs afs binfmt_misc proc smbfs autofs iso9660 ncpfs coda devpts ftpfs devfs mfs shfs sysfs cifs lustre tmpfs usbfs udf fuse.glusterfs fuse.sshfs curlftpfs ecryptfs fusesmb devtmpfs"

Rainy Day Scenarios:

csis345@csis345-vm:~$   perl linenum.pl
error: incorrect number of arguments

usage: linenum.pl [filename]

csis345@csis345-vm:~$   perl linenum.pl /etc/passwd /etc/updated.conf
error: incorrect number of arguments

usage: linenum.pl [filename]

csis345@csis345-vm:~$   perl linenum.pl /etc/
error: argument must be a file

usage: linenum.pl [filename]


Add at least 5 more scenarios in your Word document.

Explanation / Answer

#!/usr/bin/perl
use warnings;
use strict;

# check if the number of arguments is correct
if (@ARGV != 1) {
die "error: incorrect number of arguments usage: $0 [filename] ";
}
my $filename = $ARGV[0];
# check if the filename exists and the filename should not be a directory
if(-e $filename && ! -d $filename){
# check if the file is non-empty
if(-s $filename){
# check if the file is readable
if(-r $filename){
my $lineno;

while(<>){
printf("%04d", $lineno++); # format the numbers to be displayed in 4 decimal places
print ": $_"; # print the line from the file
}
print " ";
}
else{
die "error: argument must be a readable file usage: $0 [filename] ";
}
}
else{
die "error: argument must be a non-empty file usage: $0 [filename] ";
}
}
else {
die "error: argument must be a file usage: $0 [filename] ";
}

Rainy Day Scenarios:

if the file is empty

csis345@csis345-vm:~$   perl linenum.pl /etc/updated.conf
error: argument must be a non-empty file usage: linenum.pl [filename]

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote