Sleuthing a “Gotcha”: Perl’s Returns Last Evaluated Statement

Here I am coding up some exercises in my first love of a language, Perl (Its the CPAN, I tell you). In my console, I kept getting a strange result:


Hi Fred! You are the first one here!
1
Hi Barney! I've also seen Fred here!
2
Hi Wilma! I've also seen Fredand Barney here!
3

I’m wondering where the heck the integers are coming from (God?). I had no primitive debugging in the form of embedded say or print. I examined the code, of course, thinking I must be the problem:


sub greet_all {
    state @greeted_people;

    my $greeted_name = shift;

    # deal with "unitialized error"
    if ( @greeted_people ) {
         say "Hi $greeted_name! I've also seen ", join(' and ', @greeted_people), " here!";
     } else {
         say "Hi $greeted_name! You are the first one here!";
     }

     push @greeted_people, $greeted_name;
}

Aha! Perl was the problem. You see, without an explicit return, Perl returns the value of the last evaluated statement. This allows for some nice shortcuts and some fewer keystrokes. It also prints integers unexpectedly, too :-)

So, what did I do? I just returned a blank string…


return " ";

Apparently, Ruby does this too.


Leave a comment