Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re^4: setting PERL_PERTURB_KEYS & PERL_HASH_SEED in a perl file

by haukex (Archbishop)
on Jul 18, 2016 at 12:57 UTC ( [id://1167961]=note: print w/replies, xml ) Need Help??


in reply to Re^3: setting PERL_PERTURB_KEYS & PERL_HASH_SEED in a perl file
in thread setting PERL_PERTURB_KEYS & PERL_HASH_SEED in a perl file

Hi gravid,

Could you show a short example of the kind of sort you're doing (some sample input data, brief code and expected output)? I'm almost certain there's a better solution than messing with Perl's internal hash settings and re-starting the interpreter.

Regards,
-- Hauke D

Replies are listed 'Best First'.
Re^5: setting PERL_PERTURB_KEYS & PERL_HASH_SEED in a perl file
by gravid (Novice) on Jul 18, 2016 at 13:12 UTC

    Hi,

    Lets say we have this hash:

    $hash{a} = 0; $hash{b} = 1; $hash{c} = 0; $hash{d} = 3;

    The expected output is:

    a = 0 c = 0 b = 1 d = 3

    or

    c = 0 a = 0 b = 1 d = 3

    (note how 'a' & 'c' are switched)

    Both are correct!

    However, for consistency, I rather have always the same output.

    The code that I'm using is:

    foreach my $k ( sort { $hash{$a} <=> $hash{$b} } keys %hash ) { print "$k = $hash{$k}\n"; }

    Thx

    Guy

      Hi gravid,

      Yep, there's a better solution than messing with Perl's internals :-)

      my %hash = ( a=>0, b=>1, c=>0, d=>3 ); foreach my $k ( sort { $hash{$a} <=> $hash{$b} or $a cmp $b } keys %ha +sh ) { print "$k = $hash{$k}\n"; }

      Always outputs:

      a = 0 c = 0 b = 1 d = 3

      Background: If the comparison of the values (<=>) shows they are equal it returns zero, so then the second part of the or expression is evaluated, comparing the keys.

      Update: See the multi-field sort in How do I sort an array by (anything)? That FAQ answer also references this article: Far More Than Everything You've Ever Wanted to Know About Sorting

      Hope this helps,
      -- Hauke D

        Thx Hauke!

        This is the solution.

        Works for me great :)

        Thx

        Guy

      sort { $hash{$a} <=> $hash{$b} || $a cmp $b }
      I was sure that whatever written inside a BEGIN statement is hapannig before everything else, so I'm not sure why my first attempt did't wok

      So you thought that the Perl code in a BEGIN block would be run by the perl interpreter before the perl interpreter was initialized? Surely it is not hard to see why that is not the case.

      - tye        

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1167961]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (5)
As of 2024-03-29 07:46 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found