Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 138
  • Last Modified:

storing @AoA (or any data structures) in classes

I'm trying my hand out at some OOP perl.  It's a bit confusing.

Suppose I have a class MyClass.  There are functions such as readCSV and printCSV.  I've done some small class examples using scalar variables stored as "member" data.  But how is this done with arrays, hashes, and complex data structures?  In this example, I'd like to store the @AoA as member data in the class instance.


use strict;
 
package MyClass;
 
sub new
{
   my $class = shift;
   my %params = @_;
   my $self = {};
   bless($self,$class);
   return $self;
}
 
sub readCSV 
{
   my $self = shift;
   my $file = shift;
   open(FILE,"$file");
   while(<FILE>){
      chomp;  
      push push $self->@AoA, [split /,/]; #???
   }
   close(FILE);
}
 
sub printCSV
{
   my $self = shift;
}
 
1;

Open in new window

0
mock5c
Asked:
mock5c
  • 2
2 Solutions
 
kawasCommented:
just assign the your member name to be the array (or array reference), i.e.
sub new
{
   my $class = shift;
   my %params = @_;
   my $self = {};
   #store your array
   $self->{array_of_array} = @AoA;
   bless($self,$class);
   return $self;
}

Open in new window

0
 
Adam314Commented:
This:
    $self->{array_of_array} = @AoA;
will interpret @AoA in scalar context, returning the number of elements in @AoA, and so setting $self->{array_of_array} to the number of elements in @AoA.

You will have to us a reference to @AoA.  You could do either of these:
    #Create a reference to @AoA.  Changes to @{$self->{array_of_array}} will change @AoA
    $self->{array_of_array} = \@AoA;  
   
    #Create a reference to a new array containing the same data as @AoA.
    #Changes to @{$self->{array_of_array}} will not change @AoA
    #    (but changes to the contents of rows will change the same rows in @AoA)
    $self->{array_of_array} = [@AoA];

See here for more on references:
    http://perldoc.perl.org/perlreftut.html
    http://perldoc.perl.org/perldsc.html
    http://perldoc.perl.org/perllol.html

sub readCSV 
{
    my $self = shift;
    my $file = shift;
    open(FILE,"<$file") or die "Could not open $file: $!\n";
    my @lines=<FILE>;
    chomp @lines;
    $self->{lines} = [map {[split/,/]} @lines];
    close(FILE);
}
 
sub PrintCSV
{
    my $self=shift;
    foreach (@{$self->{lines}}) {
        print join(",", @$_) . "\n";
    }
}
 
1;

Open in new window

0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now