http://qs321.pair.com?node_id=592884


in reply to Re^2: Stuck on packages
in thread Stuck on packages

A simple getter method might look like:
sub get_foo { my $self = shift; return $self->{foo}; }
Example:
use strict; use warnings; package Foo; sub new { my $class = shift; return bless { foo => "bar!\n" }, $class; } sub get_foo { my $self = shift; return $self->{foo}; } 1; my $foo = Foo->new; print $foo->get_foo;
The above code will print bar! There are many modules on CPAN that can create getter and setter methods for you, Class::Accessor and Class::MethodMaker are a couple of examples

Replies are listed 'Best First'.
Re^4: Stuck on packages
by Yoda_Oz (Sexton) on Jan 04, 2007 at 06:43 UTC
    ok i understand now!
    so what would i need to code if i wanted something like this?
    sub new { my $class = shift; return bless { engine => "engine", wheels => "wheels", etc...}, $c +lass; } sub get_foo { my $self = shift; return $self->{engine,wheels,etc...}; }
    how do i make it an array or hash or whatever?
      Within the getter method you can access any of the attributes, so you just have to put them in the data structure you are wanting to return, such as:
      sub get_as_array { my $self = shift; return [ $self->{engine}, $self->{wheels} ]; }
      Is there something else you were wanting to do? If you dump the return of this, you'll see it's in an array.
        ARRAY(0x18012b8) is the output.
        here is the entire code:
        #!/usr/bin/perl package Foo; sub new { my $class = shift; return bless { engine => "engine", wheels => "wheels" }, $class; } sub get_as_array { my $self = shift; return [ $self->{engine}, $self->{wheels} ]; } 1; my $foo = Foo->new; print $foo->get_as_array;