1 / 8

PERL: part II hashes, foreach control statements, and the split function

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 “%”

Télécharger la présentation

PERL: part II hashes, foreach control statements, and the split function

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. PERL: part IIhashes, 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”)

  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 (@words) { print "$word\n"; } • Variable $word takes the successive values of @words. 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 Street”; @personal = 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

More Related