Main Content

$ is atomic and % and @ are molecular - Perl

Archive - Originally posted on "The Horse's Mouth" - 2011-08-20 09:46:33 - Graham Ellis

"When do I use a $, when do I use an @, and when do I use a % ?" That is a frequently asked question on a Perl course, where a delegate had dabbled with a bit of Perl ahead of time.

You use @ if you're referring to the whole of a list - in other words a complete collection. If you're a chemist, you may refer to methane as CH4 - and that's a molecule - a collection.

And you use $ if you're referring to a single scalar value rather than a colelction as a whole. It might be a quite separate scalar variable, or it might be an individual member of a list in which cas you'll put its index number (position) in the list in square brackets. The $ is a single value - an atom to the chemist.

Here's an example to show what I mean

  # Whole list with @
  @menu = ("Coffee","Muffin","Plate","Toast","Tea");
  print "@menu\n";
  
  # Individual member with $
  $menu[2]="Croissant";
  print "$menu[1]\n";
  
  # Whole list again - with changed individual member
  print "@menu\n";


And when we run that ...

  munchkin:ap1 grahamellis$ perl lz
  Coffee Muffin Plate Toast Tea
  Muffin
  Coffee Muffin Croissant Toast Tea
  munchkin:ap1 grahamellis$


There's a sample showing various examples [here] from yesterday's Perl course ... and there are older examples (which are included and documented in our training notes that accompany the courses [here] and [here].





So - what about the % character? That's used to access a hash. A list (which we saw above) is a collection of sequentially numbered scalars, from 0 up, whereas the members of a hash are (typically) named rather than numbered, and aren't in any particuar ordered sequence.

Here's a code sample like the one above - this time using a hash:

  # Whole hash with %
  %menu = (Bob => "Coffee",Brenda => "Muffin",Thomas => "Plate",
       Felicity => "Toast",Sasha => "Tea");
  print %menu,"\n";
  
  # Individual member with $
  $menu{Thomas}="Croissant";
  print "$menu{Brenda}\n";
  
  # Whole hash again - with changed individual member
  print %menu,"\n";


And running that:

  munchkin:ap1 grahamellis$ perl hz
  SashaTeaFelicityToastBobCoffeeThomasPlateBrendaMuffin
  Muffin
  SashaTeaFelicityToastBobCoffeeThomasCroissantBrendaMuffin
  munchkin:ap1 grahamellis$


With a hash, you can't simply loop through a series of index numbers to reference items by their position number - you'll normall use the keys function. There's an example here - again, we cover that in detail on our Perl courses.