cptg286k programming - perl chapter 5 & 6: hashes & basic i/o
TRANSCRIPT
CPTG286K Programming - Perl
Chapter 5 & 6: Hashes & Basic I/O
Hash Variables
• A hash is a collection of scalar data, selected by arbitrary scalars called keys
• Hash elements are ordered internally to facilitate access (don’t try to control this order)
• Hashes resemble Rolodex filing cards whose indexes are similar to hash keys, and the card entries similar to the hash value
Accessing Hashes
• Hash elements are separate scalar variables, accessed by a string index (the key)
• Curly brackets are used to enclose the key:$fred{“aaa”} = “bbb”; # key “aaa”, value “bbb”
$fred{234.5} = 456.7; # key “234.5”, value 456.7
print $fred{“aaa”}; # prints “bbb”
$fred{234.5} += 3; # becomes 459.7
Un/winding Hashes
• Unwinding a hash moves key-value pairs into an array or a copy of a hash
@fred_list = %fred; # unwind %fred into
# array @fred_list
• Winding creates a new hash from an existing array or copy of a hash
%barney = @fred_list; # create %barney from
# array @fred_list
%barney = %fred; # faster winding method
More Hash Windings...
%smooth = (“aaa”,“bbb”,“234.5”,456.7);
# create %smooth from literal values
%backwards = reverse %normal;
# swap keys and values; beware of identical values,
# which after swapping become non-unique keys
Hash Functions
• The following functions are used to process hashes:– Keys– Values– Each– Delete
Keys function
• In list context, keys ($hashname) yields a list of all current keys in a hash %hashname
• In scalar context, keys ($hashname) yields the number of elements (key-value pairs) in the hash
Examples using keys function
$fred{“aaa”} = “bbb”;
$fred{234.5} = 456.7;
@list = keys(%fred); # @list gets (“aaa”, 234.5) # or (234.5, “aaa”) due to
# arbitrary ordering
foreach $key (keys (%fred))# process each $key in list
{ # generated by keys function
print “At $key we have $fred{$key}\n”:
# print key and value pair
}
if (keys(%somehash))
{ # if keys() not zero, %somehash is not empty }
if (%somehash)
{ # if True (not zero), %somehash is not empty }
Values Function
• The values %hashname function yields a list of all current values in %hashname
%lastname = (); # force %lastname empty
$lastname{“fred”} = “flinstone”;
$lastname{“barney”} = “rubble”;
@lastname = values(%lastname); # @lastname may be
# (“flinstone”, “rubble”) or
# (“rubble”,”flinstone”) due
# to arbitrary ordering
Each function
• The each %hashname function returns a key-value pair for each element of %hashname
while (($first, $last) = each(%lastname))
{ # process each %lastname element
# $first is key, $last is value
print “The last name of $first is $last\n”;# print key and value pair
}
Delete function
• The delete %hashname{“key”} function removes the key-value pair from %hashname
%fred = (“aaa”,”bbb”,234.5,34.56);
# %fred has two elements
delete $fred{“aaa”};
# %fred is now (234.5, 34.56)
Hash Slices
• Using slices, two or more hash elements can be accessed at a time
• Hash slices can be used with variable interpolation
• Hash slices can also be used to merge a smaller hash into a larger one
Examples of Hash Slices
# doing this:
$score{“fred”} = 205;
$score{“barney”} = 195;
$score{“dino”} = 30;
# is same as:
($score{“fred”},$score{“barney”},$score{“dino”}) = (205,195,30);
# and same as:
@score{“fred”,”barney”,”dino} = (205,195,30);# slices and variable interpolation
@players = qw(fred barney dino);
print “scores are: @score{@players}\n”;
More hash slice examples
# Merging a smaller hash into a larger one
# Get values of %score, and copy them into the
# %league hash whenever the keys of %score match
# the keys of %league
%league{keys %score} = values %score;
# equivalent to %league = (%league, %score);
Input from <STDIN>
• STDIN can be used to read data in both list and scalar contexts
• In list context, @a = <STDIN>; reads lines until end of file (or CTRL-D)
• In scalar context, $a = <STDIN>; reads input up to newline, or whatever $/ is set to
• <STDIN> also accepts the $_ scalar variable: $_ = <STDIN>;
Example reading STDIN to $_
# The following code…while (defined ($line = <STDIN>))
{chomp $line;print $line;}
# …is same as:while (<STDIN>) # or while ($_ = <STDIN>)
{chomp; # or chomp $_;print; # or print $_;}
Input from the <> operator
• The <> operator behaves like <STDIN>, but takes data from file(s) specified by the @ARGV array
• By default, the element(s) of @ARGV contain command-line arguments (filenames specified at the command-line)
• @ARGV can be redefined in a program
Example of input from <>
#!/usr/bin/perl
# this program (kitty) works like UNIX cat
# invoke with kitty file1 file2 file3
# the following lists the contents of this file:
# kitty kitty.pl
#
while (<>) # read files from command-line
{
print $_; # print output
}
Example redefining @ARGV
#!/usr/bin/perl
# this program (kitty) works like UNIX cat
# and lists contents of files “aaa”, “bbb”,
# and “ccc”
#
@ARGV = (“aaa”,“bbb”,“ccc”);
while (<>) # read files from command-line
{
print $_; # print output
}
Output to STDOUT
• PERL can use print or printf functions to produce output
• The print function returns 1, unless an I/O error occurs
• The printf function allows greater degree of control, and is similar to the printf function in C
STDOUT examples
$a = print(“Hello ”, “world”, “\n”);
# $a is set to 1 when print succeeds
printf “%15s %5d %10.2f\n”, $s, $n, $r
# prints $s as a 15 character string field
# prints a space
# prints $n as a 5 character decimal integer
# prints a space
# prints $r as a 10 character 2 decimal place
# floating point field
# prints a newline