in reply to Variable/if question...
There are a few problems with the code you have posted (as noted by others and which I won't repeat here). However, once all of those little bugs are fixed you also might want to consider reworking the logic of the code. Here is a cleaned up version of your code, largely following your posted code in level and style (ie, not trying to add anything beyond what you are already doing), but rearranging the logic somewhat:
#!/usr/bin/perl -w use strict; # first initialize necessary variables: my $err_msg = "Authorization Failed: please try again\n"; my $cusr = 'bob'; my $cpword = 'pass'; # next obtain the user's data: my($usr, $pword); print "What is your username? "; $usr = <STDIN>; chomp($usr); print "Please enter your password:\n"; $pword=<STDIN>; chomp($pword); # now we can authenticate or die unless ($usr eq $cusr and $pword eq $cpword) { die $err_msg; } print "Authentication Complete!\n"; # authorized file processing may ensue: my @lines; my $file = 'memberlist.txt'; open (FILE, $file) || die "Can't open $file: $!"; while(<FILE>){ push @lines,$_; } close FILE; # now do whatever with @lines. print @lines; __END__
I am not saying the above is optimal --- it can be shortened and simplified further. But, we've now broken out the logic into 4 self contained tasks: 1)setting initial values, 2)obtaining user authentication data, 3)perform the authentication or die with a message, 4)read and otherwise process the file. In your original, those last three tasks were all intermixed in the code rather than proceeding logically from one stage to the next. This reordering not only reduces the complexity of the code (no more nested conditionals), it makes it easier to code and test section by section in the first place --- which can greatly help in avoiding (or at least catching early) the scattering of syntactical errors and ommissions that crept into your code. It is also good practice for when you want to break out logical tasks into subroutines.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: Variable/if question...
by tretin (Friar) on Nov 07, 2001 at 08:23 UTC |