an intro to perl, pt. 2 hashes, foreach control, and the split function
TRANSCRIPT
![Page 1: An Intro to Perl, Pt. 2 Hashes, Foreach Control, and the Split Function](https://reader036.vdocuments.net/reader036/viewer/2022082819/56649f275503460f94c3f954/html5/thumbnails/1.jpg)
An Intro to Perl, Pt. 2
Hashes, Foreach Control, and the Split Function
![Page 2: An Intro to Perl, Pt. 2 Hashes, Foreach Control, and the Split Function](https://reader036.vdocuments.net/reader036/viewer/2022082819/56649f275503460f94c3f954/html5/thumbnails/2.jpg)
Hashes (Associative Arrays)
• Arrays with string indices• Each index is called a key• Different braces than arrays ({} not [])• Use the % sigil to symbolize a hash
![Page 3: An Intro to Perl, Pt. 2 Hashes, Foreach Control, and the Split Function](https://reader036.vdocuments.net/reader036/viewer/2022082819/56649f275503460f94c3f954/html5/thumbnails/3.jpg)
Example Hashes
• $numbers{“one”}=”1”; Assigns 1 to key “one”• $numbers{“two”}=”2”; (accessed as a scalar)• $numbers{“three”}=”3”;
• %numbers=(“one”,”1”,”two”,”2”,”three”,”3”);Creates hash with indices one, two, three and
values of 1, 2, and 3
![Page 4: An Intro to Perl, Pt. 2 Hashes, Foreach Control, and the Split Function](https://reader036.vdocuments.net/reader036/viewer/2022082819/56649f275503460f94c3f954/html5/thumbnails/4.jpg)
Hash Control
• while(($key, $value) = each %numbers){print "$key $value\n”;}
Prints out individual Key-value pairs for the hash
![Page 5: An Intro to Perl, Pt. 2 Hashes, Foreach Control, and the Split Function](https://reader036.vdocuments.net/reader036/viewer/2022082819/56649f275503460f94c3f954/html5/thumbnails/5.jpg)
Foreach Control Statement
• For loop designed for processing arrays, hashes, and lists.
• @word=(“This”, “is”, “an”, “array”);• foreach $word (@words){
print "$word\n";}@myNames = ('Larry', 'Curly', 'Moe');
foreach (@myNames) {print $_ . “\n”;}
![Page 6: An Intro to Perl, Pt. 2 Hashes, Foreach Control, and the Split Function](https://reader036.vdocuments.net/reader036/viewer/2022082819/56649f275503460f94c3f954/html5/thumbnails/6.jpg)
The Split Function
• Splits a string using a specific delimiter• @fields=split " ", $string;If $string = “The quick brown fox”@fields= (“The”, “quick”, “brown”, “fox”)• Default delimiter is a space “ “• $info = "Caine:Michael:Actor:14, Leafy Drive";
@personal = split(/:/, $info);