Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling

Re: printing hash values, (don't need the keys)

by trammell (Priest)
on Jul 06, 2006 at 22:07 UTC ( #559684=note: print w/replies, xml ) Need Help??

in reply to printing hash values, (don't need the keys)

One problem with your code is that you're reading the entire file into memory when you don't need to. Here's an alternative that doesn't (untested):
my $data_file = "ActiveItems2.txt"; open(DAT, $data_file) || die("Could not open file: $!"); my %seen; while (<DAT>) { chomp; $seen{$_}++; } close(DAT); for (sort keys %seen){ print "$_\n"; }

Replies are listed 'Best First'.
Re^2: printing hash values, (don't need the keys)
by GrandFather (Sage) on Jul 06, 2006 at 22:32 UTC

    If you omit the chomp then you can:

    my $data_file = "ActiveItems2.txt"; open(DAT, $data_file) || die("Could not open file: $!"); my %seen; $seen{$_}++ while <DAT>; print for sort keys %seen; close(DAT);

    Another interesting variant (although it may suffer the slurp problem) is to use a hash slice:

    @seen{<DAT>} = (); # Hash slice assignement print for sort keys %seen;

    It's worth seeing the hash slice a few times to remember that it is there and what the syntax is. Like many things in Perl, occasionally it is exactly what you need to achieve a clean solution to a problem. Perhaps not in this case though. :)

    DWIM is Perl's answer to Gödel

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://559684]
[thezip]: Our cat is single-handedly (pawed-ly?) solving our field mouse problem. About four critters in the last week alone.
[thezip]: Amazing speed and stealth in that one.
[GotToBTru]: You can't tunafish, but some seafood companies can tunafish. More fun with English.
[virtualsue]: a veterinarian told me to cut down on my cat's food. i said, when i do that she just catches more mice
[thezip]: My dogs are also excellent mousers, at least that's what they tell me.
[GotToBTru]: our beagle has dispatched 3 rabbits to the Great Hutch in the Sky since March.
[thezip]: I can always tell when the dogs have been mousing, as there is a concentric ring of mud around the end of their snouts when they do.

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (16)
As of 2017-11-17 19:53 GMT
Find Nodes?
    Voting Booth?
    In order to be able to say "I know Perl", you must have:

    Results (272 votes). Check out past polls.