80 likes | 86 Vues
PERL: part II hashes, foreach control statements, and the split function. By: Kevin Walton. 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 “%”
E N D
PERL: part IIhashes, foreach control statements, and the split function By: Kevin Walton
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”)
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;
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
Foreach Control Structure • Foreach works like the each function, only with arrays instead of hashes EX: foreach $word (@words) { print "$word\n"; } • Variable $word takes the successive values of @words. All elements of the list are printed in order.
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.
Split Example $info = “Kevin,Walton,Student,19,Race Street”; @personal = split(/,/, $info); • Split breaks up the $info string so that: @personal = (“Kevin”, “Walton”, “Student”, “19”, “Race Street”);
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