Perl: array operations: push and pop
According to Perl, an idea can push into your head, then pop out.
For previous information about arrays, just search this site. You may want to start here. For information about getting Perl up and running on your computer, try Perl in the search box at the right:)
With Perl, you can add an element to the end of an array using push. Let’s imagine you want to add “Hans” to the array @guestlist. You might do so as follows:
push(@guestlist, “Hans”);
Likewise, you can remove the last element from an array using pop. Perhaps, now, you want to remove Hans from @guestlist and store him in the variable $scratched. You might do so this way:
$scratched=pop(@guestlist);
Via the Perl program below, the user can ride the roller-coaster of forming a guest list for a party. Note that the guests are added to the array @partyguests using push, while the last one is later removed using pop:
#!/usr/bin/perl
@partyguests=qw(Bill Trish Steve Flo);
print “\n\nHere’s our guest list: @partyguests.\n\n”;
print “Let’s invite Tom, Sheila, and Suzy.\n\n”;
push (@partyguests,”Tom”);
push(@partyguests,”Sheila”);
push(@partyguests,”Suzy”);
print “Here’s our guest list with the additions: @partyguests.\n\n”;
print “Oh, no: there’s only room for six. We’ll scratch Suzy:(\n\n”;
$scratched=pop(@partyguests);
print “We’ll make it up to you, $scratched.\n\n”;
print “This is our updated guest list: @partyguests.\n\n”;
Don’t worry, Suzy; from what I heard, you didn’t miss much:)
I’ll be talking more about Perl array operations.
Source:
McGrath, Mike. Perl in easy steps. Southam: Computer Step, 2004.
Jack of Oracle Tutoring by Jack and Diane, Campbell River, BC.
Leave a Reply
You must be logged in to post a comment.