Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

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

by leocharre (Priest)
on Mar 17, 2006 at 21:42 UTC ( [id://537590]=note: print w/replies, xml ) Need Help??


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

This is buggy as far as scoring, but the idea is here.

#!/usr/bin/perl -w use strict; my $text = qq|If you have a question on how to do something in Perl, o +r you need a Perl solution to an actual real-life problem, or you're unsure why something you've tri +ed just isn't working... then this is the place to ask. However, you might consider asking in the chatterbox first (if you're +a registered user). The response time tends to be quicker, and if it turns out that the pr +oblem/solutions are too much for the cb to handle, the kind monks will be sure to direct y +ou here.|; # build lines hash my %lines; my $k=1; for (split(/\n/,$text)){ $lines{$k}=$_; $k++; } # score hash # put your words here, and the value for each my %score_guide = ( 'for'=>1, 'the'=>1, 'if'=>2, 'you'=>3, 'moguai'=>40 ); # this will hold key= line num, val= score my %score_results =(); # score each line for (keys %lines){ $score_results{$_} = score_line($lines{$_}); } # feedback for (keys %score_results){ print "line $_ score $score_results{$_}\n"; } sub score_line { my ($string)=$_[0]; # my $score=0; for (sort keys %score_guide){ while ($string=~s/\b\Q$_\E\b//i){ # corrected by ikegami $score+=$score_guide{$_}; } } return $score; }

output:

[leo@mescaline ~]$ perl scorelines.pl line 1 score 8 line 2 score 6 line 3 score 1 line 4 score 9 line 5 score 4 line 6 score 6

Replies are listed 'Best First'.
Re^2: Increasing key/values held in a Hash from an Array
by ikegami (Patriarch) on Mar 17, 2006 at 22:03 UTC

    /\b$_\b/
    should be
    /\b\Q$_\E\b/
    since the OP said he had an array of words (as opposed to regexps).

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others imbibing at the Monastery: (8)
As of 2024-04-23 13:06 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found