Main Content

Lead characters on Perl variable names

Archive - Originally posted on "The Horse's Mouth" - 2009-08-24 21:38:14 - Graham Ellis

Perl variable names mostly start with a special character:

$ for a scalar variable - that's a variable that can hold an integer, a float, a string, a reference, or a compiled regular expression (that last not being terribly common).

@ for a list - that's an ordered collection of scalars, indexed from position "0" upwards. Since each individual member is a scalar, it can be an integer, a float ... etc, and it is referenced as an individual variable by a $ in front, and square brackets around the elements.

% for a hash - that's an unordered collection of scalars, indexed by other scalars. A good parallel here is a database table with two columns - one of which is a unique key and the other a value associated with it. Since members are scalars, they are referenced with a $ in front, and curly braces around the individual elements indicate members

& for a code variable - i.e. a "sub". You'll find that the & character is often omitted as a pair of round brackets - with or without a parameter - also indicate "run this code".

NO SPECIAL CHARACTER IN FRONT for a file handle. Conventionally written all in capitals ("I know what I am doing - I really DO intend to use a file handle here!") but they could be written lower case. File handles are used in limited places - open, close, seek, read <xxx>, etc and are really a sort of lightweight object, with handles also being connected to pipes, sockets, etc - they are (in reality) stream handles.

* for a typeglob - a use of "one of each of the above". Again, not very commonly used - the major use is for providing a mechanism for handling an 'array' of files; you can't do this directly with a list as a list is of scalars, and a file handles is not a scalar.

Here's some code including training examples of each of those, and also showing you context - how a list (for example) can be taken as a series of elements, a string made up of all the elements of a list, or the length of a list depending on the code surrounding the reference you make to it. These examples from the Perl for Larger Projects course I am running at present - day one's revision of Perl Basics.

$abc = "jashjkshjkhjkerhjkerhkert";
@stuff = ("Sage","Onion","feathers","foam rubber",66);
%henry = ("August", "Barbados", "September", "New Zealand",
  "October", "Tallin", "November", "Hull", "July",
  "Hawaii", "June", "Penge", "May", "Cape Town");
 
# Context Revision ---------------------
 
$"=", "; # Set separator to ', '
 
print @stuff,"\n"; # list context
print scalar(@stuff),"\n"; # Scalar context - no. els
print @stuff + 0 ,"\n"; # Scalar context - no. els
print "@stuff","\n"; # double quotish context
print (join(", ",@stuff),"\n"); # MUCH More maintainable.
 
print "$stuff[1] - @stuff[1] - \n"; # First good, second baaaaad
print @stuff[0,3,4],"\n"; # list slice
print @stuff[1..3,-1,2],"\n"; # list slice - any ole order!
print $#stuff,"\n"; # Index number of top element (i.e. length -1)
 
# String handling revision ----------------
 
$him = "John";
$message = "\"Don't do that\" $him said\n";
$message2 = qq("(please) Don't do that" $him said\n);
$message3 = <<"zSfs";
"I would rather you didn't to that " explained $him
"since there is already another dog in the bath and
the two of them will splash fearsomcley"
zSfs
print $message;
print $message2;
print $message3;
 
# " - a string operator
# ' - a literal string
# ` - run at shell / command level and save result
 
# Hash Revision ------------------------------
 
print %henry,"\n";
print (join(", ",%henry),"\n");
for ${widget} (keys(%henry)) {
  print "$widget and we visit $henry{$widget}\n";
  }
 
@movals = sort keys %henry;
print "@movals\n";
 
sub bylength {
  length($b) - length($a);
  }
 
@movals = sort bylength keys %henry;
print "@movals\n";
 
# Special variable types -------------------------
 
$a = "Henry";
$b = "Whillemena Smith";
$dx = &bylength; # Run a code variable
print "$dx\n";
 
$stuff = "Goods, Possessions, Chattels";
*nuvver = *stuff; # package deal - @stuff, %stuff, $stuff, &stuff, stuff
print "@nuvver\n";
print "$nuvver\n";


If this is a useful revision, then you're set for the Perl for Larger Projects or Using Perl on the Web courses. If you're thinking "I need to learn this", then please come on our Perl Programming course. There are varients for those who have programmed before, and for complete novices.

To complete my example, here is the output from running that program:

Dorothy-2:pl grahamellis$ perl fred
SageOnionfeathersfoam rubber66
5
5
Sage, Onion, feathers, foam rubber, 66
Sage, Onion, feathers, foam rubber, 66
Onion - Onion -
Sagefoam rubber66
Onionfeathersfoam rubber66feathers
4
"Don't do that" John said
"(please) Don't do that" John said
"I would rather you didn't to that " explained John
"since there is already another dog in the bath and
the two of them will splash fearsomcley"
SeptemberNew ZealandJunePengeJulyHawaiiMayCape
TownNovemberHullOctoberTallinAugustBarbados
September, New Zealand, June, Penge, July, Hawaii, May,
Cape Town, November, Hull, October, Tallin, August, Barbados
September and we visit New Zealand
June and we visit Penge
July and we visit Hawaii
May and we visit Cape Town
November and we visit Hull
October and we visit Tallin
August and we visit Barbados
August, July, June, May, November, October, September
September, November, October, August, June, July, May
11
Sage, Onion, feathers, foam rubber, 66
Goods, Possessions, Chattels
Dorothy-2:pl grahamellis$