[newbie] how to walk values on a column in perl

J

John

Hi gurus,


If I want to walk the colunms on one array of array, How do you do
that?

This is my case

@a = (
[qw/a b c d e/],
[qw/1 b m e f/],
[qw/c b n g h/],
[qw/j b l z y/]
),


and I want to check all values on a row to see if are the same. (on
this case all for column 1).

How I could do that? I always can transpose the array and operate over
all the elements in the row, but I think that must be a way to work
over the columns, without change the original array.


Any idea.

Thanks a million for your help

J
 
A

Andreas Kahari

John wrote: said:
and I want to check all values on a row to see if are the same. (on
this case all for column 1).

my $val;
foreach my $row (@a) {
if (!defined $val) {
$val = $row->[1];
next;
}

if ($row->[1] ne $val) {
die "Column is not uniform\n";
}
}
 
T

Tad McClellan

John said:
If I want to walk the colunms on one array of array, How do you do
that?

This is my case

@a = (
[qw/a b c d e/],
[qw/1 b m e f/],
[qw/c b n g h/],
[qw/j b l z y/]
),


my @col1 = map $_->[1], @a;
 
G

Greg Bacon

: If I want to walk the colunms on one array of array, How do you do
: that?

There's more than one way to do it:

#! /usr/local/bin/perl

use warnings;
use strict;

sub transpose {
my $max = 0;
for (@_) {
$max = @$_ if @$_ > $max;
}

my @t = map [], 1..$max;

for (@_) {
my @a = (@$_, map undef, 1..$max-@$_);

for (@a) {
my $top = shift @t;
push @$top => $_;
push @t, $top;
}
}

wantarray ? @t : \@t;
}

sub column {
my $i = shift;

my @col = map $_->[$i], @_;

wantarray ? @col : \@col;
}

sub equal {
return 1 unless @_;

my $first = shift;
for (@_) {
return unless $_ eq $first;
}

1;
}

sub equal_column_transpose {
my $i = shift;

my @t = transpose @_;

print "transpose: column $i: ";
if (equal @{ $t[$i] }) {
print "equal\n";
}
else {
print "not equal\n";
}
}

sub equal_column_slice {
my $i = shift;

print "slice: column $i: ";
if (equal column $i, @_) {
print "equal\n";
}
else {
print "not equal\n";
}
}

## main
my @a = (
[qw/a b c d e/],
[qw/1 b m e f/],
[qw/c b n g h/],
[qw/j b l z y/]
);

foreach my $col (0..4) {
foreach my $cmp (\&equal_column_transpose, \&equal_column_slice) {
$cmp->($col, @a);
}
}

: [...]

Hope this helps,
Greg
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,141
Messages
2,570,813
Members
47,357
Latest member
sitele8746

Latest Threads

Top