The next function is "pop" which chops off the highest element from an array, and returns that value. Naturally, there is a push function, but it is not demonstrated. The sort command is shown, however.
The final part of the program shows how to implement the equivalent of a "case statement", since there is no "switch" command in Perl as there is in C or C++ languages. It uses the power of matching and regular expressions in order to achieve the same result.
#!/usr/bin/perl # Using Simple Perl Functions print "Enter pattern:"; $pattern = <STDIN>;Enter pattern: Josh
# Scan through the passwd file. Create an array of lines with search pattern @people = `cat /etc/passwd | grep $pattern`; print @people, "\n";jeddy:8J2fhwdxUqEiM:2626:1999:Joshua Eddy:/home/atlas2/jeddy:/usr/local/bin/bash
# This section manipulates the strings grabbed from the passwd file $j=0; for ($i = 0; $i<= $#people; $i++) {$_ = $people[$i]; # Use "split" to break the string into separate elements between colons @passwd_data[0..6]= split(":"); # Using double quotes for the delimiter # This field contains the full name of the user print $passwd_data[4]; print "\n"; # Use "split" to break apart first and last names @temp = split(/ /, $passwd_data[4]); # Use the slash for a delimiter # Use the function "pop" to pull off the last name $lastnames[$j] = pop(@temp); #print last name first, then what's left in @temp (first name) print $lastnames[$j],", ", @temp , "\n\n"; $j++; }Joshua Eddy
$,="\n "; # Change the print separator to a carriage return # Use the "sort" function to sort the array print "Sorted by last name: ",sort @lastnames; print "\n";Sorted by last name:
$,=""; # Reset the print separator to null # Emulating the "switch" statement print "Do they like Perl?\n"; while (<>) # Infinite loop requesting keyboard response { $answer = "I don't understand. Type 'Q' to quit"; REPLY: # Skip other statements at "last REPLY". Exit loop at "goto". { # Beginning "y" followed by possibly "es" at end, and ignore case /^y(es)?$/i && do { $answer= "Perl is Kewl!"; last REPLY; }; # Beginning "n" followed by possible "o", ignore case /^no?$/i && do { $answer = "What a shame..."; last REPLY; }; # The exact word "maybe", but ignore case /^maybe$/i && do { $answer = "Let's learn more."; last REPLY; }; # Beginning "q", or the word "quit", ignoring case. Jump out of "while" /^q(uit)?/i && do { $answer = "QUIT"; print "Thanks!\n";goto EXIT; }; } print $answer, "\n"; print "But, do they like Perl?\n"; } EXIT: print "Going on....\n";Do they like Perl? yes