Hi Duncan and James,

On Tue, 9 Feb 2016 14:58:05 +0000
Duncan Ferguson <duncan.fergu...@opsview.com> wrote:

> I disagree – hashes are not weird – they are incredibly useful.  It is just
> an array indexed by a word instead of a number  ☺
> 

I agree with Duncan here. Hashes are an integral part of idiomatic Perl and one
should learn how to use them properly and use them often - when appropriate.
For some resources for learning about hashes see:

        * http://perl-begin.org/topics/hashes/

Otherwise, James’s code suffers from many bad idioms. For how to improve it,
see:

        * http://perl-begin.org/tutorials/bad-elements/

(Note: perl-begin.org is a web site that I maintain.)

Below is one comment on Duncan's code:

> 
> 
> Here is some working code that may help
> 
> ===
> 
> #!/usr/bin/perl
> 
> use strict;
> 
> use warnings;
> 
> 
> 
> my @array = ( qw/ 11_ 22_ 33_ 33_ 33_ 44_ 44_ 55_ / );
> 
> 
> 
> my %results;
> 
> 
> 
> # create a hash of arrays
> 
> for my $item (@array) {
> 
>     push(@{ $results{$item} }, $item);
> 
> }
> 
> 
> 
> # For each entry in the hash
> 
> for my $key (sort(keys(%results))) {
> 
>    # make a local array back out of what is stored in the hash
> 
>     my @arr = @{ $results{$key}};
> 
>     print "key=$key:", $/;
> 
>     # print out the indexes of items in the local array
> 
>     print "  $key$_",$/ foreach (0 .. $#arr)
> 

Since you're only using key and the length of the $results{$key} array
reference, you might as well just store a count which you can increment using
either of the ++ operators. Moreover, do you wish to preserve the order of the
occurrences?

Regards,

        Shlomi Fish

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to