Home: Perl Programming Help: Beginner:
firstidx, 'array of arrays'


Nov 26, 2012, 2:46 AM

Views: 3140
firstidx, 'array of arrays'

I have a 'two dimensional array' and need to find the index (row number) of an element in column.

I've tried this:

 my $index= firstidx { $_ eq '7' } @servces[][1];

but it doesn't work. Can you please help me?

Chris Charley

Nov 26, 2012, 11:48 AM

Views: 3120
Re: [orange] firstidx, 'array of arrays'

my $index= firstidx { $_->[1] == 7 } @servces;

(This post was edited by Chris Charley on Nov 26, 2012, 11:49 AM)


Nov 26, 2012, 11:55 AM

Views: 3118
Re: [orange] firstidx, 'array of arrays'

Strictly speaking, perl does not support multi-dimensional arrays. Proper use of references largely hides this fact.

In your case, the symbol @services refers to a single dimensional array. Each element of that array is a reference. Each reference refers to a list of scalars (one "row" in your notation). The data that you think of as 'column 1" consists of the second (indexes start with zero) element of each of these arrays. To treat that colulmn as a list, you must explicitly extract it.

my @col1 = map ($_->[1]) @services; 
my $index= firstidx { $_ eq '7' } @col1;

Update: Chris Charley neatly combined these two statements into one.
Good Luck,

(This post was edited by BillKSmith on Nov 26, 2012, 9:16 PM)