Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Looping through an object property containing an array 1

Status
Not open for further replies.

rawkin

Programmer
Sep 23, 2003
11
AU
Hi,

I have an object with a property containing an array, eg;

---------------------------------------
#!/usr/bin/perl
use strict;

my $Obj = main->new;

exit 0;

sub new {
my $class = shift;
bless {
property => ['zero', 'one', 'two', 'three']
}, $class;
}
---------------------------------------

I can reference each element of the property's array via;
print "$Obj->{'property'}[0]'}\n";

I'm not sure how I can loop through each element of the array .. I've tried;

foreach my $value ($Obj->{'property'}) {
print "$value\n";
}

This just results in "ARRAY(0x82aed20)".

Any ideas?

thanks,

Pete
 
You need to dereference $Obj->{property} as an array, like so (Note the @{...}):
Code:
#!perl
use strict;
use warnings;

my $Obj = main->new;

foreach my $value ([b]@{$Obj->{'property'}}[/b]) {
  print "$value\n";
}

exit 0;

sub new {
  my $class = shift;
  bless {
    property => ['zero', 'one', 'two', 'three']
  }, $class;
}

[b]Output:[/b]
zero
one
two
three
See
perldoc perlreftut
perldoc perldsc
perldoc perlref
perldoc perllol



 
Ahh, of course! :) That's done the trick.

thanks very much.

Pete
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top