Ok, so first of all, thanks AnomolousMonk. The text file did have a blank line at the end. This means that my initial understanding of the problem was wrong: I had thought that $username was being interpolated like I expected in the matching expression but not in the print statement.
Now, indeed, when that blank line is read, the match is successful, and so the print get's called, but the variable $username is empty. This means that $username is failing to be interpolated in BOTH the match AND the call to print.
But that is not the whole story. Here's a slightly modified script: (the #NEW comment marks the one line I've added to the original):
use strict;
my $username;
my $color;
while(<>){
chomp;
s/"//g;
($username,$color) = (split /,/,$_)[2,3];
print STDOUT "$username\n"; #NEW
if ("agag" =~ m/($username)/){print STDOUT "here is the username:
+$username\n"}
}
when I run this with the same invocation as before (perl test.pl test.txt), here's the output I get (and by the way, the text file still ends with a blank line):
adad
agag
ahah
here is the username:
Wierd, huh? The $username comes out as expected when used in the "naked" print statement (the line marked #NEW), but it fails to be interpolated in BOTH the match AND the print statement in the following line.
OK, now a second point here. (it get's wierder!) Corion tests the script by "hard coding" the data from the text file into the script like so:
use strict;
my $username;
my $color;
while(<DATA>){
chomp; s/"//g;
($username,$color) = (split /,/,$_)[2,3];
if ("agag" =~ m/($username)/){
print STDOUT "here is the username: $username\n"
}
}
__DATA__
"ADELMAN","John","adad","Ray"
"AGAN","John","agag","Aditya"
"AHMED","John","ahah","Conor"
Now, when I run this on my machine, I get the output I'm looking for -- i.e.
here is the username: agag
So, I'm still stumped. Is this a scoping problem (like $username goes out of scope when we get into the "if" statement)? Is there something I don't understand about the diamond operator (that's what Corion's finding suggests to me)? Could this be some sort of file permission issue (I'm running linux, and working in the shell as a regular user. and no, I'm not willing to run this script as root).