Am 29.01.2012 12:12, schrieb Pradeep Patra:
> Hi,
> I am tryting out a perl program and I am having issue in
> dereferencing the arrays or arrayreferences.
First question: why are you creating a reference to an array of arrayrefs?
> my $array_refs;
> my @array;
> for ($i=0;$i < 3; $i++)
> {
> @array = func1($i)
> push(@{$array_refs},\@array);
> }
I think $array_refs should better be @array_refs. First, it matches the
name better and also I don't see a point in using a reference here. In
addition, you don't need the @array outside of the loop. So keep it inside.
Code could be:
my @array_refs;
for my $i (0..2) {
my @array = func1($i);
push @array_refs, \@array;
}
or even better - no need to use a loop, make use of map:
my @array_refs = map [func1($_)], (0..2);
> for my $s (@{$array_refs})
> {
> my $c = $s->func2(); # This function works on actual arrays
Exactly. It is working on an array. The the array does not have a
function called "func2". Your objects in the array might have this
function. You need to loop over the array elements.
It is always good to provide minimal code which one can run, including
your func1 and func2.
So try this:
--------------------8<--------------------
package xxx;
sub new { bless {('name' => $_[1])}, $_[0]; }
sub func2 { $self=shift; print "Hi, I am func2 $self->{name}\n" }
package main;
sub func1 { return (xxx->new($_[0]), xxx->new($_[0] . ", version2")) }
my @array_refs = map [func1($_)], (0..2);
for my $arrayref (@array_refs) {
for my $element (@$arrayref) {
$element->func2();
}
}
--------------------8<--------------------
- Wolf
|