Main Content

Variable Types in Perl

Archive - Originally posted on "The Horse's Mouth" - 2008-12-15 23:37:02 - Graham Ellis

In Perl, you have "autovivification" where variables are created when they have a values set in them, without the need to declare them. Some authorities will tell you that they are also "autotyped" in that Perl knows what to store in them automatically too, and to some extent that's true ... but the leading character is also important in at least some of the type decisions.

$ - a scalar, to hold an integer, a float, a string, a reference or a regular expression
@ - a list, to hold an ordered (referenced by counter) collection of scalars
% - a hash, to hold an unordered (reference by scalar key) collection of scalars
& - code, to hold a sub or method
No initial letter - a file handle - to hold the structure through which a file is accessed
* - a typeglob, used occasionally to handle a grouping of one of each of the above

Earlier today, I put together an example that sets up one of each variable type ...

$abc = "text"; # Scalar variable - string, number, reference or regex
@def = (1,4.5,"hello",$abc,$abc); # List variable - a number of scalars
%ghi = (Wales => "Rugby", England => "Cricket"); # Hash variable - keyed scalars
sub jkl {print "Hello Wurld\n"; } ; # Code variable - named piece of code
open (MNO,">demo.gunk"); # File handle variable - for file reference
*pqr = *abc; # Typeglob - one of each of the above


and then makes use of it, or (in the case of lists, hashes and typeglobs) the scalars within:

print "$pqr ... \n"; # Same as $abc
print MNO "This is filed\n"; # To file - not seen on output
print (jkl,"\n"); # Runs jkl code, also prints "1" - its return value
print $ghi{Wales},"\n"; # Printing from a hash - note curlies
print $def[1],"\n"; # Printing from a list - note squares
print $abc,"\n"; # Straightforeward printing of a scalar!


See Full source code of example - and here are the results:

Dorothy:plpw grahamellis$ perl vartypedemo
text ...
Hello Wurld
1
Rugby
4.5
text



Illustration - on a private Perl course run which I ran at a customer's offices in Cambridgeshire