in reply to Expression, but is it regular?

OeufMayo is exactly correct, but just to add a little detail regarding your logic: here's your code rearranged into a more traditional format:
if ($in{username} =~ /^(\[a-zA-Z]{2})/ || ' ') { $dirtype = $1 || 'other'; }
First of all, the "or" in the "if" statement will never trigger because "if" always tests for "truth." In other words, the "if" is saying "if the regular expression is true OR the string " " is true." Unfortunately, " "is NEVER true in Perl, so if your regex doesn't match the if is skipped entirely.

Second of all, IF the regular expression DOES match (triggering the code between the brackets and populating $1 at the same time) THEN in your case $1 is always guaranteed to be true (because it will contain two A-Za-z letters. Letters always evaluate to "true." Because the first expression in your short-circuit operation ($1) is always true, your program will never get to the 'other' value.

This is why OeufMayo resorted to a ternary operator, which is just a short-hand way to write another if/then statement. Here it is rewritten for clarity:

my $dirtype; if ( $in{username} =~ /^([a-zA-Z]{2})$/ ) { $dirtype = $1; } else { $dirtype = 'other'; }
This way the logic is all straigthened out.

And then there's the backslash in your regex. :-D

Gary Blackburn
Trained Killer

Replies are listed 'Best First'.
Re: Re: Expression, but is it regular?
by Rhandom (Curate) on May 08, 2001 at 18:29 UTC
    You were right the second time. That is a good way to explain things. Usually it is best to start out with a multi-line piece of code, rather than trying to write a very complex one liner. It is easier to debug the multi-line piece and then simplify it down into a one liner.

    One clarification... (Unfortunately, " "is NEVER true in Perl)... There are some things that are true that you wouldn't think are true (in this case " " actually is). Try some of the following...
    perl -e 'print "1\n" if "";' perl -e 'print "1\n" if " ";' perl -e '@a=(); print "1\n" if @a;' perl -e '@a=(undef); print "1\n" if @a;'

    Empty strings and empty lists do evaluate to false. Strings and lists with even one item evaluate to true, even if that one item is itself false.

    my @a=qw(random brilliant braindead); print $a[rand(@a)];
Re: Re: Expression, but is it regular?
by web-yogini (Novice) on May 12, 2001 at 05:22 UTC
    Thank you so much for the excellent logic lesson. I stripped it apart like you suggested, and now it is working wonderfully.

    Thanks again for all the responses! You Perl Monks are such enlightened brethren! ; )

    Sad Gurunath Maharaj ki jai!