Skip to Main Content
Learning Perl, 5th Edition
book

Learning Perl, 5th Edition

by Randal L. Schwartz, Tom Phoenix, brian d foy
June 2008
Beginner content levelBeginner
352 pages
11h 16m
English
O'Reilly Media, Inc.
Content preview from Learning Perl, 5th Edition

Persistent, Private Variables

With my we were able to make variables private to a subroutine, although each time we called the subroutine we had to define them again. With state, we can still have private variables scoped to the subroutine but Perl will keep their values between calls.

Going back to our first example in this chapter, we had a subroutine named marine that incremented a variable:

sub marine {
  $n += 1;  # Global variable $n
  print "Hello, sailor number $n!\n";
}

Now that we know about strict, we add that to our program and realize that our use of the global variable $n isn’t allowed anymore. We can’t make $n a lexical variable with my because it wouldn’t retain its value.

Declaring our variable with state tells Perl to retain the variable’s value between calls to the subroutine and to make the variable private to the subroutine:

use 5.010;

sub marine {
  state $n = 0;  # private, persistent variable $n
  $n += 1;
  print "Hello, sailor number $n!\n";
}

Now we can get the same output while being strict-clean and not using a global variable. The first time we call the subroutine, Perl declares and initializes $n. Perl ignores the statement on all subsequent calls. Between calls, Perl retains the value of $n for the next call to the subroutine.

We can make any variable type a state variable; it’s not just for scalars. Here’s a subroutine that remembers its arguments and provides a running sum by using a state array:

use 5.010; running_sum( 5, 6 ); running_sum( 1..3 ); running_sum( 4 ); ...
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

Learning Perl, 6th Edition

Learning Perl, 6th Edition

Randal L. Schwartz, brian d foy, Tom Phoenix
Beginning Perl

Beginning Perl

Curtis Ovid Poe
Learning Perl 6

Learning Perl 6

brian d foy
Mastering Perl

Mastering Perl

brian d foy

Publisher Resources

ISBN: 9780596520106Supplemental ContentErrata Page