Stories
Slash Boxes
Comments
NOTE: use Perl; is on undef hiatus. You can read content, but you can't post it. More info will be forthcoming forthcomingly.

All the Perl that's Practical to Extract and Report

use Perl Log In

Log In

[ Create a new account ]

dami (6728)

dami
  (email not shown publicly)

Journal of dami (6728)

Wednesday February 27, 2008
02:23 PM

package in main file : careful with initializations!

[ #35782 ]
A colleague of mine came with a program looking more or less like this. What do you think is the output ?

  use strict;
  use warnings;

  my $obj = Obj->new(11);
  print $obj->meth, "\n";

  #-----------
  package Obj;
  #-----------
  use strict;
  use warnings;

  my $foo = 22;
  my $bar = 33;

  sub new {
    my ($class, $arg) = @_;
    my $self = bless {arg => $arg}, $class;
  }

  sub meth {
    my ($self) = @_;
    return "$self->{arg} / $foo / $bar";
  }

It looks so obvious : the answer must be 11 / 22 / 33. But this is wrong! We get trapped by being so used to external packages, where everything is initialized at load time.

Here, everything is in the same file. So the main program starts, new and meth get called before $foo and $bar are initialized, and the result is 11 / / , with a warning about uninitialized values!

The Fine Print: The following comments are owned by whoever posted them. We are not responsible for them in any way.
 Full
 Abbreviated
 Hidden
More | Login | Reply
Loading... please wait.