> > From: Graeme McLaren [mailto:[EMAIL PROTECTED]
> > Sent: Wednesday, March 08, 2006 3:57 PM
> > To: [email protected]
> > Subject: counting scalar array elements question
> >
> > Hi all, I have an array question:
> >
> > If I have a variable, $var, and it contains an array how would I be able
> > to
> > easily count the number of elements in the array? I've tried creating a
> > new
> > array and pushing the original array on to it but that creates an array
> > of
> > arrays.
> >
> > Basically I have:
use strict;
use warnings;
> > my $var = [
> > 'a',
> > 'b',
> > 'c'
> > ]
# shorter:
my $var=[ qw/ a b c / ];
> > and I tried:
my @array;
#or:
my @array=();
(sidenote: the second form must be used in contexts where the code is
persistent/preloaded and used several times, to ensure that @array is always
empty when the next execution hits the code again. Of course only *if* it
should start empty and not accumulate between executions)
> > push @array, $var;
> >
> >
> > and got:
> >
> > @array=[
> > [
> > 'a',
> > 'b',
> > 'c'
> > ]
> > ]
You probably got this AoA (array of arrays) by using
use Data::Dumper;
Dumper [EMAIL PROTECTED];
The outer [] stems from the \ after Dumper.
The data structure of @array itself is only, formulated as list:
@array=( ['a','b','c'] )
An arrayref is a scalar (holding a reference to an array), so after pushing it
to an empty array, you just get an array with one element, the pushed scalar.
> > Using my original array which is assigned to scaler, what I need is:
> >
> > @array = [
> > 'a',
> > 'b',
> > 'c'
> > ]
> >
> >
> > So I can do:
> >
> > my [EMAIL PROTECTED];
> >
> >
> > Can anyone shed any light on this or suggest a better way of doing this?
>
>Timothy Johnson am Donnerstag, 9. März 2006 01.06:
> You need to dereference your array ref.
>
> my $count = @{$var};
the same, shorter, but more hiding what's going on:
my [EMAIL PROTECTED];
> Or in some circumstances it might make more sense to explicitly use
> scalar context:
>
> my $count = scalar @{$var};
One of these circumstances would be for example, since print provides list
context:
print scalar @$var;
Hans
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>