LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   unblessed references in lists in Perl (http://www.linuxquestions.org/questions/programming-9/unblessed-references-in-lists-in-perl-456956/)

thelonius 06-21-2006 11:43 AM

unblessed references in lists in Perl
 
Hello,

I wonder what it would be the right way to treat anonymous references in lists. I have a list like this:

Code:

$element = ['one', 'two', {'3' => 'three', '4' => 'four'}, 'five'];
and when in a loop I want to print it, I get the error "Can't call method "treat" on unblessed reference":

Code:

treat( $element);

sub treat {
  @array = @{$_[0]} if ref( $_[0]) eq "ARRAY";
  @array = values %{$_[0]} if ref( $_[0]) eq "HASH";

  for( @array) {
    if( ref( $_) eq "HASH") {
      treat $_;
    }
    else {
      print "$_ ";
    }
  }
};

I get 'one two' and the error message, and not the 'one two three four five'.

Thank you in advance.

puffinman 06-21-2006 01:43 PM

Is this in a package file? Is there another method somewhere also called treat? Sounds like perl thinks treat is a method call, which would only make sense to call with an instance of the object created by the package. It seems odd that it wouldn't error at your first call to treat, because the array ref is also unblessed. The only difference between the two calls is the parentheses...

thelonius 06-21-2006 02:09 PM

Quote:

Originally Posted by puffinman
The only difference between the two calls is the parentheses...

...and this was the error not to use parentheses for the second call. Now it works.

Here is the complete correct version (pay attention to the 'my' declaration of the inner array):

Code:

#!/usr/bin/perl
$element = ['one', 'two', {'3' => 'three', '4' => 'four'}, 'five'];
treat( $element);
sub treat {
  my @array;
  @array = @{$_[0]} if ref($_[0]) eq "ARRAY";
  @array = values %{$_[0]} if ref($_[0]) eq "HASH";
  for (@array) {
    if( ref( $_) =~ /(HASH)|(ARRAY)/) {
      treat( $_);
    }
    else {
      print "$_ ";
    }
  }
}

Thanksssssss!!!!!!!!


All times are GMT -5. The time now is 08:19 AM.