in reply to calling a sub from an if statement

tye is correct, however, his solution leaves a touch to be desired. Simply move the %msgs has to the top of the file. And I would recommend taking SteveAZ98's method of initializing the hash. Using => is a lot cleaner than the comma separated key/value pairs. Much more obvious which messages goes with which key, particularly if you decide to add to the list.

You could also simplify in a few places. Where you have
if ($method ne "GET") { if ($method ne "POST") { msg(400); } }
use instead
if ($method ne "GET" && $method ne "POST") { msg(400); }
Note that you probably want a return or and exit at this point, otherwise, you're going to continue executing code, after you've kicked an error message out. This is usually not what you want to do.

You can also simplify your file reading with this:
open(FILE1, $ARGV[0]); @lines = <FILE1>;
And, of course, as a responsible programmer, you'll be wanting to close the file when you're done with it. <G>

--Chris

e-mail jcwren

Replies are listed 'Best First'.
RE: (jcwren) Re: calling a sub from an if statement
by tye (Sage) on Jul 24, 2000 at 00:19 UTC

    I don't know what you don't like about using BEGIN, perhaps you could elaborate. As for moving %msg to the top of the file, I specifically avoided that route because there are several problems with it. First, it can be hard to maintain. One little pass through moving things around to try to clean up your code and suddenly you've got a call to the sub before the data is initialized again.

    Second, I consider it a bad habit since when you get into more advanced coding, it isn't sufficient. For example, if this becomes a module:

    package My::Module; # Keep this next line at the very top, please: %msgs= (400=>"Bad Request",...); [...] use My::OtherModule; [...] sub msg { die "HTTP/1.0 $_[0] $msgs{$_[0]}\n"; }
    Then all we need is:
    package My::OtherModule; [...] sub import { msg(400) if ! $valid; [....] }
    and we run back into the same problem.