Skip to Content
Intermediate Perl
book

Intermediate Perl

by Randal L. Schwartz, brian d foy, Tom Phoenix
March 2006
Intermediate to advanced
278 pages
6h 49m
English
O'Reilly Media, Inc.
Content preview from Intermediate Perl

Chapter 7. Subroutine References

So far, you’ve seen references to three main Perl data types: scalars, arrays, and hashes. We can also take a reference to a subroutine (sometimes called a coderef).

Why would we want to do that? Well, in the same way that taking a reference to an array lets you have the same code work on different arrays at different times, taking a reference to a subroutine allows the same code to call different subroutines at different times. Also, references permit complex data structures. A reference to a subroutine allows a subroutine to effectively become part of that complex data structure.

Put another way, a variable or a complex data structure is a repository of values throughout the program. A reference to a subroutine can be thought of as a repository of behavior in a program. The examples in this section show how this works.

Referencing a Named Subroutine

The Skipper and Gilligan are having a conversation:

sub skipper_greets {
  my $person = shift;
  print "Skipper: Hey there, $person!\n";
}

sub gilligan_greets {
  my $person = shift;
  if ($person eq "Skipper") {
    print "Gilligan: Sir, yes, sir, $person!\n";
  } else {
    print "Gilligan: Hi, $person!\n";
  }
}

skipper_greets("Gilligan");
gilligan_greets("Skipper");

This results in:

Skipper: Hey there, Gilligan!
Gilligan: Sir, yes, sir, Skipper!

So far, nothing unusual has happened. Note, however, that Gilligan has two different behaviors, depending on whether he’s addressing the Skipper or someone else.

Now, ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Perl Debugged

Perl Debugged

Peter Scott, Ed Wright
Think Perl 6

Think Perl 6

Laurent Rosenfeld, Allen B. Downey
Beginning Perl

Beginning Perl

Curtis Ovid Poe
Pro Perl

Pro Perl

Peter Wainwright

Publisher Resources

ISBN: 0596102062Supplemental ContentErrata Page