learningmanylang has asked for the wisdom of the Perl Monks concerning the following question:

I am learning the basics of Perl, after finishing learning the basics of Groovy, Python, C#, Scala and adding onto my Java this semester.
My main goal is to have a program read in a file that contains a number on each line like

1 2 3 3 2 2 1 2

and take those numbers and print them out in order with a "*" mark for every occurrence, making a histogram type program. I can post my code in Java or something else if it would help anyone understand what I am talking about.
The output I need looks like:
1:**
2:****
3:**

open(FILE, '/location/data/p4.txt') or die "Cant't open file: $!\n"; my %myhash = (); my @data = (); chomp(@data = <FILE>); foreach (@data) { %myhash = (@data => $k++); } foreach $k (sort {$a <=> %b} keys %myhash) { print "$myhash{$k} : ". '*' x $myhash{$k} . "\n"; }

This is what I have done so far from using code in another problem I made. How do I up the count? It doesn't seem like my loop is working properly on this problem either.

Replies are listed 'Best First'.
Re: Learning Perl, Hashes Help
by toolic (Bishop) on Apr 29, 2014 at 00:56 UTC

    Tip #1 from the Basic debugging checklist... warnings

    use warnings; my %myhash = (); my @data = (); chomp(@data = <DATA>); foreach (@data) { $myhash{$_}++; } foreach $k (sort {$a <=> $b} keys %myhash) { print "$k : ". '*' x $myhash{$k} . "\n"; } __DATA__ 1 2 3 3 2 2 1 2

      Awesome, I actually had it like that first, but I had $myhash{$k}++; instead of $myhash{$_}++;
      Perl has been like reading Chinese compared to all of the other wordier languages I'd been working with.

Re: Learning Perl, Hashes Help
by Jim (Curate) on Apr 29, 2014 at 01:33 UTC

    Instead of doing this…

    open(FILE, '/location/data/p4.txt') or die "Cant't open file: $!\n +";

    …do this…

    use strict; use warnings; use autodie qw( open close ); # ... my $file = shift; # The input file name is a command-line argument open my $fh, '<:encoding(ASCII)', $file; # Or whatever the correct + character encoding is # ... close $fh;

    And instead of doing this…

    my %myhash = (); my @data = (); chomp(@data = <FILE>); foreach (@data) { %myhash = (@data => $k++); }

    …do this…

    my %total_values_by; while (my $value = <$fh>) { chomp $value; $total_values_by{$value}++; }