Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Array as Object Data Member

by fattahsafa (Sexton)
on Dec 16, 2015 at 19:44 UTC ( [id://1150541]=perlquestion: print w/replies, xml ) Need Help??

fattahsafa has asked for the wisdom of the Perl Monks concerning the following question:

I need to build a class with two arrays as data members of 6 other members, as follows:
sub new { my $class = shift; my $self = { _DataMember0 => shift, _DataMember1 => shift, _Array0 => shift, _Array1 => shift, }; bless $self, $class; } sub get_DataMember0 { my ($self) = @_; return $self->{_TestCaseDataFiles}; } sub get__Array0 { my ($self) = @_; return <QUESTION> }
Now, what should I use in place of <QUESTION> ? Another thing, how should I send a value for Array0? by reference of by value? Thanks,

Replies are listed 'Best First'.
Re: Array as Object Data Member
by stevieb (Canon) on Dec 16, 2015 at 20:00 UTC

    First, because you're shifting single items inside of new(), both arrays need to be arefs when sent in. In your get__Array methods, you want to return the array that you have stashed in $self->{_ArrayN};. Here's a full example that shows how you can return either a reference to the array you have stored, or return it as a list instead:

    use warnings; use strict; package Test; sub new { my $class = shift; my $self = { _DataMember0 => shift, _Array0 => shift, }; bless $self, $class; } sub get__Array0{ my $self = shift; if (wantarray){ # caller wants a list (dereference the ref before return) return @{ $self->{_Array0} }; } else { # caller wants an array reference return $self->{_Array0}; } } package main; my $aref = [1, 2, 3]; my $test = Test->new(1, $aref); # get it as a list my @array = $test->get__Array0(); # parens not needed, only used for c +larity # get an aref instead my $array_reference = $test->get__Array0(); print "$_\n" for @array; print "$array_reference->[0]\n";

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1150541]
Approved by ww
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (7)
As of 2024-04-19 09:13 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found