Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer

Re^4: Prototype like sort()?

by RonW (Parson)
on Jan 26, 2018 at 19:33 UTC ( #1207980=note: print w/replies, xml ) Need Help??

in reply to Re^3: Prototype like sort()?
in thread Prototype like sort()?

While I would not recommend it, $a and $b are only special in that they are predeclared and used by sort. Otherwise, you can use them like any other package variable:

sub mysort (&@) { my $coderef = shift; while (@_ > 1) { $a = shift; $b = $_[0]; my $c = $coderef->(); print " $c"; # do sorting } print "\n"; } mysort { $a <=> $b } qw(1 3 2);

But, it is a bad idea to use $a and $b except with sort

But, could use 2 other variables. Just have to declare them.

Replies are listed 'Best First'.
Re^5: Prototype like sort()?
by Laurent_R (Canon) on Jan 27, 2018 at 19:09 UTC
    While I fully agree with Marshall that prototypes should generally be avoided (that is, unless you really know what your doing and why), and with you that, similarly, $a and $b should also be avoided most of the time, I think that we shouldn't be too dogmatic about that and that it does make sense to use both prototypes and the $a and $b special variables if you're going to write your own sort subroutine.

    BTW, the List::Util module documentation illustrates some cases where it makes perfect sense to use the $a and $b variables in a context that has nothing to do with sorting.

    In the example that I gave in Re: Prototype like sort()?, I'm localizing $a and $b before using them to avoid (at least, I hope) any side effects with their use somewhere else.

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (8)
As of 2019-05-22 20:57 GMT
Find Nodes?
    Voting Booth?
    Do you enjoy 3D movies?

    Results (140 votes). Check out past polls.

    • (Sep 10, 2018 at 18:53 UTC) Welcome new users!