Presentation is loading. Please wait.

Presentation is loading. Please wait.

CPTG286K Programming - Perl Chapter 5 & 6: Hashes & Basic I/O.

Similar presentations


Presentation on theme: "CPTG286K Programming - Perl Chapter 5 & 6: Hashes & Basic I/O."— Presentation transcript:

1 CPTG286K Programming - Perl Chapter 5 & 6: Hashes & Basic I/O

2 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

3 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

4 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

5 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

6 Hash Functions The following functions are used to process hashes: –Keys –Values –Each –Delete

7 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

8 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 }

9 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

10 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 }

11 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)

12 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

13 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”;

14 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);

15 Input from STDIN can be used to read data in both list and scalar contexts In list context, @a = ; reads lines until end of file (or CTRL-D) In scalar context, $a = ; reads input up to newline, or whatever $/ is set to also accepts the $_ scalar variable: $_ = ;

16 Example reading STDIN to $_ # The following code… while (defined ($line = )) { chomp $line; print $line; } # …is same as: while ( )# or while ($_ = ) { chomp;# or chomp $_; print;# or print $_; }

17 Input from the <> operator The <> operator behaves like, 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

18 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 }

19 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 }

20 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

21 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


Download ppt "CPTG286K Programming - Perl Chapter 5 & 6: Hashes & Basic I/O."

Similar presentations


Ads by Google