user4839691 user4839691 - 18 days ago 5
Perl Question

String comparisons and if statements

I am doing an assignment which asks to search for a user in a file using the

passwd
file in
/etc
.

I was able to do that, but when it cannot find a specific user it doesn't reply with the print command I have used.

Here is my code:

#!/usr/bin/perl

$file = '/etc/passwd.bak'
open ( FILE, $file ) or die "Error in reading file. Program will close";

while ( <FILE> ) {

chomp;
@field = split ( ':', $_ );

if ( $ARGV[0] eq $field[0] ) {
print "User ID: $field[2]\n" ;
print "Home Directory: $field[5]\n";
}
elsif ( @ARGV[0] ~= $field[0] {
print "User: $ARGV[0] does not exist.\n"
}
elsif ( (@ARGV > 1 || @ARGV == 0 ) ) {
print "Please enter one argument only.\n";
exit 0;
}
}


I have tried exchanging the
!=
for
ne
, but when I do that it says every argument is not found even when I know it is there.

I have tried to look in my book, and research it online with no luck.

Answer

For starters, ne is the correct operator for comparing if strings are not equal. You probably meant $field[0] ne $ARGV[0].

Aside from that, your code has some structural issues. Firstly, you check parameter counts inside of your file reading while loop. Parameter checks should be the first thing a script does, not something it does while processing. Secondly, because the "does not exist" check is inside the while loop, you'll output that message for every line that isn't the user. If your input file has 100 lines and one is your search target, you'll output one match message and 99 "does not exist" message.

I would suggest a structure like the following. Because this is for homework and should be a learning experience, I'm only giving you pseudocode, not usable perl.

if ( wrong_param_count ) {
    print "error message"
    exit
}

found_user = 0
while ( read_line_from_file ) {
    if ( this_line_is_user ) {
        print "user information here"
        found_user = 1
    }
}

if ( !found_user ) {
    print "user not found"
}
Comments