Main Content

Context in Perl

Archive - Originally posted on "The Horse's Mouth" - 2005-06-22 07:54:29 - Graham Ellis

If you write a Perl program, you refer to lists with an "@" symbol in front of the list variable name. But depending on the context of how you write it, the program may interpret it as
  1. The list contents (if the operation is normal for a list)
  2. The length of the list (i.e. the element count) if that's the only thing that makes sense
  3. A space separated string with all the items in the list joined together (if it's in double quotes)


For example:

@salad = ("apple","banana","cherry");
$salad[3] = "tomato";
$salad[8] = "fig";

print @salad,"\n"; # list context
print @salad."\n"; # scalar context
print "@salad.\n"; # double quote context


will display:


applebananacherrytomatofig
9
apple banana cherry tomato     fig.