Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re^3: question about: my $a AND sort {$a <=> $b} keys %hash

by choroba (Archbishop)
on Aug 06, 2015 at 16:21 UTC ( #1137718=note: print w/replies, xml ) Need Help??


in reply to Re^2: question about: my $a AND sort {$a <=> $b} keys %hash
in thread question about: my $a AND sort {$a <=> $b} keys %hash

I think the OP meant the following, which works:
#! /usr/bin/perl use warnings; use strict; use feature qw{ say }; sub numerically { $a <=> $b } # lexical $a not in scope my @arr = sort qw( 1 2 10 11 12 ); say "@arr"; my $a; @arr = sort numerically @arr; say "@arr";

Output:

1 10 11 12 2 1 2 10 11 12

Update: Added feature say. Thanks the Anonymous one.

لսႽ ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ

Replies are listed 'Best First'.
Re^4: question about: my $a AND sort {$a <=> $b} keys %hash
by AnomalousMonk (Bishop) on Aug 06, 2015 at 16:50 UTC

    Ah, that's interesting, because when I tried something similar, I had  $a within the lexical scope of the comparison function definition, which of course did not work:

    c:\@Work\Perl\monks>perl -wMstrict -lE "use warnings; use strict; ;; my $a = 1; ;; sub numerically { $a <=> $b } ;; my @arr = sort qw( 1 2 10 21 11 12 ); say qq{@arr}; ;; @arr = sort numerically @arr; say qq{@arr}; " 1 10 11 12 2 21 1 2 11 21 10 12
    I guess the take-away advice is that there should be a heavy application of Don't Do That™ whenever one contemplates creating lexical versions of special, non-punctuation variables.


    Give a man a fish:  <%-(-(-(-<

Re^4: question about: my $a AND sort {$a <=> $b} keys %hash
by Anonymous Monk on Aug 06, 2015 at 16:40 UTC
    Sure, if you've set PERL5OPT=Mfeature=say.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (7)
As of 2019-12-11 10:42 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?