开发者

Why wont this Chapter 4 example from 'Learning Perl 6th edition' run?

I am stuck on chapter 4 exercise 4 page 78 of Learning Perl 6th Edition. I copied the code example for the problem from page 301. I am using Perl version 5.10.1 on Ubuntu 11.04. I get errors that I cannot figure out could someone please help? I will list the code and the error message below.

#!/usr/bin/perl -w
use strict;

greet( 'Fred' );
greet( 'Barney' );

sub greet {
  state $last_person;

  my $name = shift;

  print "Hi $name! ";

  if( defined $last_person ) {
      print "$last_person is also here!\n";
 }
  else {
      print "You are the first one here!\n";
}
  $last_person = $name;
}


Global symbol "$last_person" requires explicit package name at ./ex4-4 line 8.
Global symbol "$last_person" requires explicit package name at ./ex4-4 line 14.
Global symbol "$last_person" requires explicit package name at ./ex4-4 line 15.
Global symbol "$last_person" requires explicit package name at ./ex4-4 line 20.
Execution of ./ex4-4 aborted due to compilation errors.
开发者_高级运维


You need to say use feature 'state' at the top of your script to enable state variables. See perldoc -f state.


From the manual:

Beginning with perl 5.9.4, you can declare variables with the state keyword in place of my. For that to work, though, you must have enabled that feature beforehand, either by using the feature pragma, or by using -E on one-liners. (see feature)


The pre-feature way to do it is with a closure:

{
    my $last_person;

    sub greet {

        my $name = shift;

        print "Hi $name! ",
          defined $last_person ? "$last_person is also here!"
                               : "You are the first one here!",
          "\n";

        $last_person = $name;
    }
}

The nifty say feature would also be useful in this example.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜