G'day RHC_ICT,
"However, I would like a faster processing method if at all feasible."
The following is based on these assumptions:
-
You're only searching for "goat"; not "goatee" or "goat's milk" or any other string containing the substring "goat".
-
All values in your matrix are unique.
In other words, your result won't look like: "'goat" found on rows 2, 13, and 42".
Here's my tips for faster processing:
-
Use eq to determine an exact match; not a regular expression.
-
Use a for loop instead of map or grep loops.
-
Exit the loop as soon as a match has been found.
Benchmark to compare the validity of any of those.
Here's one I did last week to compare for and map: "Re^5: How Perl can push array into array and then how retrieve [Benchmark]".
Here's some sample code:
#!/usr/bin/env perl
use strict;
use warnings;
my @array=();
$array[0][0] = "ape";
$array[0][1] = "bear";
$array[0][2] = "cat";
$array[1][0] = "dog";
$array[1][1] = "emu";
$array[1][2] = "fox";
$array[2][0] = "goat";
$array[2][1] = "horse";
$array[2][2] = "ibex";
for (qw{goat gout dog goatee ape}, "goat's milk") {
my $found = search_col(\@array, 0, $_);
print "'$_' ",
(defined $found
? "found on row $found"
: 'not found'
),
"\n";
}
sub search_col {
my ($array, $col, $search) = @_;
my $result;
for my $row (0 .. $#$array) {
next unless $array->[$row][$col] eq $search;
$result = $row;
last;
}
return $result;
}
Output:
'goat' found on row 2
'gout' not found
'dog' found on row 1
'goatee' not found
'ape' found on row 0
'goat's milk' not found
And benchmark that solution with any other solutions that are presented.
Finally, bear in mind that speed optimisations on small datasets are almost always a waste of time.
If your data really is a 3x3 matrix, I'm sure you could get the correct result by visual inspection,
faster than it would take you to type in the command to get the computer to do it for you.
In general, aim to run benchmarks on real data, not on tiny samples.
|