kettle has asked for the wisdom of the Perl Monks concerning the following question:

I'm not quite clear on why the following code errs; why can't I declare another 'my' variable with the same name?
#!/usr/bin/perl -w my ($a,$b,$c,@home); @home = (1,2,2,23,10,9); print map{$_."\n"} sort {my $a<=>my $b} @home;

This sort of problem does't always crop up so I'm really wondering why it does in this particular instance.

2006-04-13 Retitled by planetscape, as per Monastery guidelines
Original title: 'not quite clear'

Replies are listed 'Best First'.
Re: Declaring my variables in sort function?
by Corion (Patriarch) on Apr 12, 2006 at 08:09 UTC

    How "does it err" ?

    Have you looked at the documentation for the sort function ? The variables $a and $b are magical for the sort function and you should not declare them as lexical variables using my. In fact, you should not name any of your own variables $a or $b.

    As a general hint for receiving effective answers to your questions, see How (Not) To Ask A Question.

Re: Declaring my variables in sort function?
by strat (Canon) on Apr 12, 2006 at 08:10 UTC

    sort uses the "global" variables $a and $b as comparing algrothm for the sort; you can't use other variables instead

    if you try to use my-variables instead, you are useing other variables and it won't work

    sort is the reason why $a and $b aren't checked by use strict; so IMHO it's a good idea to reserve these variables to sort

    use strict; my @home = (1, 2, 23, 10, 9); print map { "$_\n" } sort { $a <=> $b } @home;

    Best regards,
    perl -e "s>>*F>e=>y)\*martinF)stronat)=>print,print v8.8.8.32.11.32"

Re: Declaring my variables in sort function?
by perladdict (Chaplain) on Apr 12, 2006 at 10:47 UTC
    Hi

    try like this

    #!/usr/bin/perl -w my (@home); @home = (21,29,2,23,10,9); print map{$_. "\n"} sort { $a <=> $b} @home;