in reply to Need help understanding variable scope in modules

The _accessible() function is an object method. It could be different for different objects. It basically ignores the actual object sent to it, and checks to see if the second argument ($1) is a key in a hash that only that function can see.

japhy -- Perl and Regex Hacker
  • Comment on Re: Need help understanding variable scope in modules

Replies are listed 'Best First'.
Re: Re: Need help understanding variable scope in modules
by nysus (Parson) on Jul 11, 2001 at 22:40 UTC
    I don't see how it could be different for different objects. Here is the structure of the module (from Conway's book):
    use strict; use warnings; package Music; use Carp; our $AUTOLOAD; { my %_attrs = ( _name => undef, _artist => undef, _publisher => undef, _ISBN => undef, _tracks => undef, _rating => undef, _room => undef, _shelf => undef, ); sub _accessible { exists $_attrs{$_[1]}} } { my $_count = 0; # These are class methods. sub get_count { $_count } # This method is global t +o the program my $_incr_count = sub { ++$_count }; sub new # Constructor called "new" { my ($class) = @_; # Gets class passed to co +nstructor $_incr_count->(); bless { # Creates a blessed referen +ce... _name => $_[1], # _artist => $_[2], # _publisher => $_[3], # _ISBN => $_[4], # _tracks => $_[5], # Simply assigns hash +key variables to _room => $_[6], # the arguments passed t +o the constructor. _shelf => $_[7], # _rating => $_[8], # _read_count => 0, }, $class; # in this class } } sub AUTOLOAD { my ($self) = @_; $AUTOLOAD =~ /.*::get(_\w+)/ or croak "No such method: $AUTOLOAD"; $self->_accessible($1) or croak "No such attribute: $1"; $self->{_read_count}++; return $self->{$1} } sub get_location {($_[0]->{_room}, $_[0]->{_shelf}) } sub set_location { my ($self, $shelf, $room) = @_; $self->{_room} = $room; $self->{_shelf} = $shelf; } sub set_rating { my ($self, $rating) = @_; $self->{_rating} = $rating; } 1;

    $PM = "Perl Monk's";
    $MCF = "Most Clueless Friar Abbot Bishop";
    $nysus = $PM . $MCF;
    Click here if you love Perl Monks

      Inheritance.
      package Person; sub eat { ... } sub drink { ... } package Alcoholic; @ISA = qw( Person ); sub drink { ... }
      Here, an Alcoholic object has its own drink method, but it inherits the eat method from Person. Similarly, something that inherits from the class you've posted could have its own _accessible method.

      japhy -- Perl and Regex Hacker