Download presentation
Presentation is loading. Please wait.
Published byFlorence Patterson Modified over 6 years ago
1
PERL: part II hashes, foreach control statements, and the split function
By: Kevin Walton
2
Hashes Hashes are similar to arrays, but use strings instead of numbers for indexing. Very similar to Maps in C++ All hash variables start with the character “%” %numbers = (“first”,”1”,”second”,”2”,”third”,”3”) Key Value “first” 1 “second” 2 “third” 3
3
Hash Commands “reverse” – changes keys into values and values into keys “keys” – returns an array of keys “values” – returns an array of values EX: %inverse_hash=reverse %numbers; Hash %numbers gets reversed, keys become values and values become keys. After reversing the hash is assigned to another variable %inverse_hash;
4
Each Function EX: while (($name, $address) = each %addressbook)
{ print "$name lives at $address\n"; } Each successive key-value pair is returned by function each, and assigned to variables $name and $address and then printed out. The each function allows for easy extraction of data from entire hashes
5
Foreach Control Structure
Foreach works like the each function, only with arrays instead of hashes EX: foreach $word { print "$word\n"; } Variable $word takes the successive values All elements of the list are printed in order.
6
Split Function The “split” function breaks up a string and places it into an array. The function uses a regular expression to divide the string Works on the $_ variable unless otherwise specified.
7
Split Example $info = “Kevin,Walton,Student,19,Race = split(/,/, $info); Split breaks up the $info string so that: @personal = (“Kevin”, “Walton”, “Student”, “19”, “Race Street”);
8
Regular Expressions Regular expressions can be used with split
EX: $_ = “Capes:Geoff::Shot putter:::Big Avenue“ @personal = split(/:+/); The string is split at any point the program encounters one or more colons
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.