Functions
The Little Engine That Could
- A Perl "function", like a lot of other stuff in computers, is a
piece of code that:
- Takes something in.
- Processes it.
- Spits something out.
- Functions are sometimes described as "engines" or "little black
boxes" or "itsy bitsy oopie whoopies" (well, not really that last one.)
- Functions simplify programming, becasue they encapsulate
frequently used tasks.
- 2 kinds of functions: Built-in and User Defined
- Built-in: Comes as part of the Perl language (or an extension.)
- User Defined: Well, um, defined by the user (programmer.)
Also called "subroutines"
- Built-in Functions
- We've already used one very frequently: print
- There are hundreds, which means that Perl has already done a
lot of work for you.
- User Defined
#!perl
$i = 0;
$n = 5;
while ($i < 10) {
print "I am about to call my subroutine...\n";
&goofy;
print "Called it!\n";
$i++;
}
print "The value of variable n is $n\n";
print "BYE!\n";
sub goofy {
print "Hi, I'm goofy.\n";
$n += 5;
}
A Useful Built-in (or 2, or 3...)
- Well, actually several useful built-ins.
- How many built-ins are in the following program?
#!perl
@dogs = qw(Baxter Opie Chaico Lassie Rover);
$i = 0;
while ($i<20) {
$random_array_index = int(rand(scalar(@dogs)));
print "I pick $dogs[$random_array_index]\n";
$i++;
}
- You will need the int(rand
blah blah thingy for Project 1