Tim,
Sorry and yes you are right. This block of code came from a big program
I
have. I had to modify some stuff to simplify before sending this out to
the mailing list but forgot to change the bracket - { to parentheis - (.
Originally I was using a reference to a hash. So sorry for those who
got
confused. Thanks for pointing this out.
Sam
Tim H. [email protected]
12/09/2005 02:04 PM
Please respond to
[email protected]
To
[email protected] (ruby-talk ML)
cc
Subject
Re: new to Ruby - pls help in translating this
Classification
List-Owner: mailto:[email protected]
List-Help: mailto:[email protected]?body=help
List-Unsubscribe: mailto:[email protected]?body=unsubscribe
Sam Dela C. [email protected] wrote:
I’m starting to use Ruby in one of my projects at work. I’m
coming from a Perl background.
In my project I would need to parse a list of numbers
(thousands of them) and then return the duplicates. In perl,
I can do this:
Perl code
%hash = {};
That doesn’t do what you think it does. In Perl, the {} here
will create a hash reference, which is a scalar datatype.
You’re assigning it to a %hash variable, which accepts LIST
data. This ends up being the same as:
%hash = ( {} );
Which creates a hash named %hash, stringifies the hash reference
and uses it as a key, and without any additional values to work
with, uses undef as a value for the key.
To see this in action:
use Data::Dumper;
my %hash = {};
print Dumper( \%hash );
Compare to:
use Data::Dumper;
my %hash = ();
print Dumper( \%hash );
Yes. You want to use parentheses.
while (<>)
{
chomp;
$hash{$_}++;
}
foreach my $key (sort keys %hash)
{
print “$key: $hash{$key}\n” if ($hash{$key} > 1);
}
HTH,
Tim H.