I am following the exercises in the O'Reilly Learning Perl book and one of them asks to write a sub greet, taking one parameter (a name) that supplies a greeting if this is the first $name that was passed to the sub, otherwise supply a greeting along with the other names that have been sent previously. (I also check if the name has been sent more than once). I am having problems getting into a certain bit of code however - I have commented where I am seeing the problem
Code:
#!/usr/bin/perl -w
use v5.14.0;
sub greet {
my $iName = $_[0];
#need some state variable that stores the parameters that have already been sent to this function on a previous invocation
state @seen_names;
#This would all be better implemented with a hash as the container type
#but in the spirit of working with beginning example sets lets just use the simpler data structures.
if (!@seen_names) {
push @seen_names, "$iName ";
print "Hello $iName, you are the first visitor to this function.\n";
} else {
my $push_name = 0;
foreach my $el (@seen_names) {
#------------------------DEBUG-----------
print "equal? ", ("$el" eq "$iName"), "\n"; #debug - the boolean looks undef
print "equal? ", ("a" eq "a"), "\n"; #debug - the boolean is true
#------------------------DEBUG-----------
if ($el eq $iName) { #debug - do not get into this if
# FIXME the next line will reprint this name unless I loop through it again from scratch (or delete then re-add after)
# neither is nice
print "hello again $iName, you have been here before, other visitors have been " , @seen_names, "\n";
} else {
print "hello $iName, previous visitors were @seen_names.\n";
$push_name = 1;
}
}
if ($push_name) {
push @seen_names, "$iName ";
}
}
}
&greet ("Greg");
&greet ("Greg");
#&greet ("Bob");
#&greet ("James");
#print &greet "Jill";
~
what am I doing wrong?
EDIT: It seemed like a good idea at the time to add each name with a space (so I could print the array without writing another loop to avoid all the names being stuck together) but that means the if I was having trouble with evaluates as false (though false doesn't seem to be 0 as I expected).