1

I'm doing a class assignment to learn about Object Oriented programming in Perl. I've got a real basic class that looks like this.

sub new{
  my $class = shift;
  my $self = {
    'Sides' => 3,
    'SL' => \@sidelengths};
  bless $self, $class;
  return $self;
  }

I've got two modules to change the sides and length(can't figure out how to modify the sidelegnths with an accessor though) but I have a requirement for my work that I have a method like this

"a method: toString() which returns all of the file attributes in a printable string. If this is done correctly, the PERL

print $file->toString() . "\n";

should print a readable summary of the file."

I already think I want to use Data::Dumper to do this and that works within a script but it sounds like I need to use it within a module and call that to print a string of whats in the object. So far I have this

sub toString{
  my $self = @_;
  Dumper( $self );
  }

Which just prints out "$VAR1 = 1"

2 Answers 2

5

What you want here is to shift an argument out of @_.

sub toString {
  my $self = shift @_;  
  Dumper( $self );
}

When you have $var = @array, that evaluates the array in a scalar context, and that returns the number of elements in the array. So, your statement my $self = @_; set $self to the number of arguments passed to toString, which in this case was 1. (The $self argument.)

Alternately, you can capture the first element of @_ this way:

sub toString {
  my ($self) = @_;  
  Dumper( $self );
}

What this does is evaluate @_ in list context since it uses list assignment. It assigns the first element of @_ to $self.

1
  • Actually the my ($self) = @_; is generally preferred, and is faster on recent versions of Perl. Dec 5, 2013 at 16:50
4
my $self = @_;

is a scalar assignment operator, so it @_ in scalar context, which is the number of elements it contains. You want to use the list assignment operator.

sub toString {
   my ($self) = @_;
   return Dumper( $self );
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.