Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw

Re: Increasing key/values held in a Hash from an Array

by fizbin (Chaplain)
on Mar 17, 2006 at 21:36 UTC ( #537589=note: print w/replies, xml ) Need Help??

in reply to Increasing key/values held in a Hash from an Array

Your data structure is malformed. You don't want the key to be the score, that is, something subject to change.

What happens if I bump up the score of something that was at 13 by two, but there's another sentence at 15? Or what if there's a sentence at 12, and one at 13, and the 12 one gets bumped up by 3 and the 13 one gets bumped up by two? What's going to happen with that data structure is that one or the other will get wiped out.

So first, we take your hash and replace it with a saner data structure:

my @scorearray = map { {score=>$_, text=>$hash{$_}} } keys %hash;

Now that that's done, what you ask is quite easy:

for my $word (@scoreWords) { my $qmword = quotemeta($word); my $regexp = qr/\b$qmword\b/; for my $scorebit (@scorearray) { $scorebit->{'score'} += 1 if $scorebit->{'text'} =~ $regexp; } }

You can even print it out in a pretty table:

printf "%-7s%s\n", "Score", "Value"; for my $scorebit (@scorearray) { printf "%5d %s\n", $scorebit->{'score'}, $scorebit->{'text'}; }
@/=map{[/./g]}qw/.h_nJ Xapou cets krht ele_ r_ra/; map{y/X_/\n /;print}map{pop@$_}@/for@/

Replies are listed 'Best First'.
Re^2: Increasing key/values held in a Hash from an Array
by Gavin (Archbishop) on Mar 17, 2006 at 23:52 UTC
    I think the Map function may suit my needs.
    But I dont understand fully what's going on Fizbin's script. Could someone explain further how to get the values into the scorearray or suggest a tutorial. I am very new to perl as you might gather and am finding these expressions difficult to follow.
    Thanks to all for their help.

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://537589]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (4)
As of 2023-09-24 07:21 GMT
Find Nodes?
    Voting Booth?

    No recent polls found