1 #!/usr/bin/perl
 2 
 3 # A short script to illustrate the differences between the various
 4 # variable types.
 5 
 6 print "SCALARS\n";
 7 print "-------\n\n";
 8 #
 9 # Variable Type: Scalars
10 #
11 # Scalars are variables that stores a single data entity, which can be
12 # any ASCII or Binary data. Scalars are defined with $varname, for
13 # exanple:
14 $myname = "Peter Pan";
15 
16 print "My name is: $myname\n\n";
17 
18 # Scalars can contain integers, and you can do some math with it:
19 $time1 = time();
20 sleep( 3 );
21 $time2 = time();
22 $timediff = $time2 - $time1;
23 print "The operation took $timediff seconds to complete\n\n";
24 
25 print "ARRAYS\n";
26 print "------\n\n";
27 #
28 # Variable Type: Arrays
29 #
30 # Areays are variables that stores various bit's of information in
31 # seperate containers, which has a numerical index. A good example, is
32 # the predefined array that holds command line arguments. To test this,
33 # invoke this script with the following command line arguments:
34 #
35 #	./intro.pl hello world
36 print "You passed the following command line arguments: ";
37 print "\'$_\' " foreach @ARGV;
38 print "\n\n";
39 
40 # You can also assign scalars to an array like this:
41 @myarray = ();	# clear any possible values from the array
42 $myconstant = "Item ";
43 for ( $t = 1; $t < 5; $t++ ) {
44 
45 	# combine the two scalars to form a new value
46 	$mytempvar = $myconstant . $t;
47 	push( @myarray, $mytempvar );	# store the value in the array
48 
49 }
50 
51 print "Items: ";
52 print "\'$_\' " foreach ( @myarray );
53 print "\n\n";
54 
55 print "HASHES\n";
56 print "------\n\n";
57 #
58 # Variable Type: Hashes ( aka associated arrays )
59 #
60 # A hash is similar to a hash, whith the distinct difference that the
61 # index is not based on a numerical position of the data, but is defined
62 # by any scalar type variable, in other words any ASCII text value:
63 %myhash = ();	# clear the hash variable of any possible values
64 %myhash = 	(
65 			"Item 1"	=>	"Apples",
66 			"Item 2"	=>	"Bananas",
67 			"Item 3"	=>	"Pears",
68 			"Item 4"	=>	"Apricots",
69 		);
70 
71 $myindex = "Item 3";
72 print "Index: \'$myindex\' stores the following value:
 \'$myhash{$myindex}\'\n\n";
73 
74 # we can also loop through all the items:
75 foreach $myindex ( keys %myhash ) {
76 
77 	$value = $myhash{ $myindex };
78 	print "Index: \'$myindex\' stores the following values: \'$value\'\n";
79 
80 }
81 print "\n";
82 
83 # you will note that the order of output of the hash values might not be
84 # in numerical order - this is normal.
85 
86 exit;


syntax highlighted by Code2HTML, v. 0.9.1