From: Bobby <cybercruiserz@yahoo.com>
Hi,
I have a large pipe delimited text file that i want to loop through
and sort out a column of data within that file. Let's call this column
$sizes. I want to group these different sizes into categories. i.e.
@sizeA = ("A","B","C");
@sizeB = ("D","E","F");
@sizeC = ("G","H","I");
1. If you have several arrays (or hashes) that contain data in the
same format and you need to do something with all of them, you should
have them all in an array or hash. In this particular case a hash:
%size = (
A => ["A","B","C"],
B => ["D","E","F"],
C => ["G","H","I"],
);
Now if you need to do something with all of them you can use
foreach my $array (values %size) {...}
or
while (my ($key, $array) = each %size) { ... }
Even if you do not know yet whether you'll need to do something with
all of them, as soon as you have several variables named $something1,
$something2, $something3, ... or $somethingA, $somethingB,
$somethingC, ... you should stick all that data in an array or hash
of somethings.
2. If you need to be able to find out easily and quickly whether
something is in a set of values, use a hash, not an array. It's much
quicker to ask whether
exists $set{$key}
in a
%set = (key1 => 1, key2 => 1, key3 => 1,...)
than whether
grep {$_ eq $key} @set
in
@set = (key1, key2, key3, ...)
If you already have the data in an array you can create the hash by
my %set = map {$_ => 1}, @list;
or
my %set, @set{@list} = ();
(In the first case you can use just
if ($set{$key})
in the second you have to use the exists().)
In this case you do not actually want to go through all the groups
and find out which one contains the key you are looking for. You want
to find out what section maps the key to. So you'd better store the
info like this:
%map = (
A => 'A',
B => 'A',
C => 'A',
D => 'B',
E => 'B',
F => 'B',
G => 'C',
H => 'C',
I => 'C',
);
and then if you want to know what group does a letter belong to you
just ask
my $group = $map{$letter};
simple and as quick as it can get.
Choose the right datastructure and the code will become obvious.
Jenda
===== Jenda@Krynicky.cz ===
http://Jenda.Krynicky.cz =====
When it comes to wine, women and song, wizards are allowed
to get drunk and croon as much as they like.
-- Terry Pratchett in Sourcery