in reply to numerology experiment

for, map, grep and split provide a little synergy here:

use strict; use warnings; my $str = "aabceezazerrfde"; my %wanted = (a => 7, e => 2, z => 26); my $tot = 0; my $counter = 0; $tot += $_ for map {++$counter; $wanted{$_}} grep {exists $wanted{$_}} + split //, $str; print "Found $counter letters totaling $tot\n";

Prints:

Found 9 letters totaling 81

Update: s/,/;/ in map - bug fix, thanks toolic.


Perl is environmentally friendly - it saves trees

Replies are listed 'Best First'.
Re^2: numerology experiment
by toolic (Bishop) on Nov 26, 2007 at 21:24 UTC
    Why does this not result in a total of 81?

    The letter "a" appears 3 times: 3x7=21

    The letter "e" appears 4 times: 4x2=8

    The letter "z" appears 2 times: 2x26=52

    21+8+52=81, not 126.

      Because of a bug ;). map {++$counter, $wanted{$_}} should have been map {++$counter; $wanted{$_}} (note the s/,/;/).


      Perl is environmentally friendly - it saves trees