Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re^3: Perl Project: Text Search

by crashtest (Curate)
on Apr 09, 2010 at 00:10 UTC ( #833674=note: print w/ replies, xml ) Need Help??


in reply to Re^2: Perl Project: Text Search
in thread Perl Project: Text Search

Your two elsif blocks don't belong in the loop. If they're in the loop, they execute for every line of the file, which is not what you want.

You only know for sure that a username wasn't in the file after you've worked through every single line of the file. In fact, since you immediately exit the program after finding and printing the information for a user, you know that if you make it through the entire while(<FILE>) loop, the username wasn't found. Print the error message at that point.

Similarly, the check that exactly one argument was provided needs to be done before you enter the while loop, not within it. Why even open the passwd file if the program wasn't run correctly, right?

Update: the indentation of your code is strange - you do realize that the if/elsif/elsif is within the while loop - hence is being executed once for every line in the input file? Nesting in Perl is controlled with curly braces ({ and }), not by indentation like in some other languages.


Comment on Re^3: Perl Project: Text Search
Select or Download Code
Re^4: Perl Project: Text Search
by Sharp (Initiate) on Apr 09, 2010 at 03:04 UTC
    Yes I am aware my indentation is strange. I am not a very good programmer lol. I just do things in a way that seems logical in my head. Which often seems stupid for everyone else. Thanks for your tip on where to put the error trapping statements. I should be able to figure it out now.
Re^4: Perl Project: Text Search
by Anonymous Monk on Apr 09, 2010 at 12:48 UTC
    I've got it working about 99% correctly now. Thanks for your help!
    #!/usr/bin/perl $filename = '/etc/passwd.bak'; if ($ARGV[0] != $fields[0]){ print "User: username does not exist.\n"; exit 0; } elsif ((@ARGV > 1) || (@ARGV == 0)){ print "Please enter at least one but only one argument.\n"; exit 0; } open(FILE, $filename) or die "Could not read from $filename, program h +alting."; while(<FILE>) { chomp; @fields = split(':', $_); if ($ARGV[0] eq $fields[0]){ print "Home directory: $fields[5]\n"; print "Shell used: $fields[6]\n"; exit 0; } } close FILE;

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://833674]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (10)
As of 2014-12-27 17:33 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (177 votes), past polls