Paul Rousseau wrote:
Hello,
I have a hash that looks like this:
my %sql_hash = ("A" => ["2", "6", ""],
"Q" => ["1", "3", ""],
"D" => ["5", "8", ""],
"X" => ["4", "2", ""],
"P" => ["3", "12", ""]);
The key is an arbitrary string (e.g. "D"). The key order is not
determined by this key string, but by the number in the first value of
the associated array value.
For example, the following code sorts the hash based on the values "2,
1, 5, 4 ,3" you see above, and prints out "The keys are: Q A P X D"
my $c;
print "keys are: ";
foreach $c (sort {$sql_hash{$a}->[0] <=> $sql_hash{$b}->[0]} keys
%sql_hash)
{
print "$c ";
}
For many of you, this is standard Perl stuff.
What I want to do is take the second entry in each value array (i.e. 6,
3, 8, 2, 12), and use it to break up a long string using the substr
function (or some other function); place each chunk in the third entry
of each value array, and base it on the sorting position of the first
value.
In other words, sort the hash in the proper order,
foreach $c (sort {$sql_hash{$a}->[0] <=> $sql_hash{$b}->[0]} keys
%sql_hash)
then somehow, pick up the second array value for each key-value pair,
add it to a running $offset variable, and apply the command,
$sql_hash{$c}->[3] = substr ($mystring, $offset, $sql_hash{$c}->[2]);
where $mystring = "stuff some blanks some words more stuff ....";
In the end, my hash looks like
%sql_hash = ("A" => ["2", "6", "ff so"],
"Q" => ["1", "3", "stu"],
"D" => ["5", "8", " words mo"],
"X" => ["4", "2", "me"],
"P" => ["3", "12", "me blanks so"]);
I have been looking at the map function to do this, but maybe there is a
better approach. I thought about sorting the hash first (based on the
first value) into an array, then using a foreach loop to obtain the
second value, add it to a running $offset variable, and applying the
substr command to update the third value.
You don't need map unless you want to make a complicated looking expr.
This should work:
use strict;
my %sql_hash = ("A" => ["2", "6", ""], # you don't need the "'s around the numbers
"Q" => ["1", "3", ""], # if they are intended to be integers
"D" => ["5", "8", ""],
"X" => ["4", "2", ""],
"P" => ["3", "12", ""],
);
my $mystring = "stuff some blanks some words more stuff ....";
my $offset = 0;
foreach (sort { $sql_hash{$a}->[0] <=> $sql_hash{$b}->[0] } keys %sql_hash) {
$sql_hash{$_}->[2] = substr ($mystring, $offset, $sql_hash{$_}->[1]);
$offset += $sql_hash{$_}->[1];
}
__END__
--
,-/- __ _ _ $Bill Luebkert ICQ=162126130
(_/ / ) // // DBE Collectibles Mailto:[EMAIL PROTECTED]
/ ) /--< o // // http://dbecoll.tripod.com/ (Free site for Perl)
-/-' /___/_<_</_</_ Castle of Medieval Myth & Magic http://www.todbe.com/
_______________________________________________
Perl-Win32-Users mailing list
[EMAIL PROTECTED]
To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs