in reply to Help fixing this piece of code
I'd suggest using strict and warnings. That would point you to one of your problems.
Learning the basic syntax would also be helpful. Nearly every line has some sort of syntax error or unusual construct that doesn't do what you think it means.
You should also show how you're calling your subroutine. I can see a couple different ways to do it, and the fixes I'd suggest would depend on which one you're wanting.
Finally, your subroutine isn't actually returning anything. So if you want it to return the mode, you'll need to tell it to do so.
Since you're just learning, I'd suggest you also use Data::Dump, and rather than build your code all at once and then wonder what's wrong, build it a step or two at a time, using Data::Dump to display the values you have so you can figure out what the next step would be.
So I'd start with this:
use strict; use warnings; use Data::Dump 'pp'; sub mode_num { my %count = (); my %opt = %{ shift @_ }; print pp(\%opt),"\n"; } my @numbers = ( 2, 3, 3, 3, 5, 7, 8, 12, 32, 44, 55, 12, 3, 23, 43, 33, 1, 4, 25, 43, 42, 1, 4, 5, 3, 3, 3 ); my $mode = mode_num(@numbers); print "Mode is: $mode\n";
With this, when you run it, you'll get the message:
Can't use string ("2") as a HASH ref while "strict refs" in use at xyz +.pl line 8.
So that means you've got a problem in line 8. So split line 8 into two operations, perhaps something like this:
my $temp = shift @_; print "temp is ", pp($temp>), "\n"; my %opt = %{ $temp };
When you run it *this* way, you'll get:
temp is 2 Can't use string ("2") as a HASH ref while "strict refs" in use at xyz +.pl line 10.
So does $temp hold what you're expecting? if so, you need to figure out what you're doing wrong on line 10. Otherwise, figure out what you're doing to get the value of $temp. Once you get $temp correct, and then correctly build %opt from it, you can merge the two steps back together. Then, add the next step and get it working the way you want. Without too much effort, you should be able to, step by step, get the mode.
Beginners frequently try to build large chunks of code and then get lost trying to figure out how to fix it. Until you gain enough experience, it's better to build it a little at a time, testing it each step of the way. That will help you be successful faster, as well as teaching yourself several interesting bits about perl during each step.
...roboticus
When your only tool is a hammer, all problems look like your thumb.
|
|---|