in reply to Print not printing

It isn't the cause of this problem, but it seems worth re-mentioning (albeit that people have often mentioned this in the past here) that $a and $b are special sort variables which (believe it or not) are not intended to work as say $c and $d would!

Example of proper use of $a and $b:

my %monk = (); $monk{ Alice }{ XP } = 130; $monk{ Bert }{ XP } = 17; $monk{ Charles }{ XP } = 20; foreach my $monk ( sort ByXP( \%monk ) keys %monk ) { print "$monk\t$monk{ $monk }{ XP }\n"; } sub ByXP { # NB $a and $b are reserved for sort routines like this # <=> is a special sort operator for sorting by numeric value my $monastery = shift; ( $monastery -> { $a }{ XP } ) <=> ( $monastery -> { $b }{ XP } ); # note that the last line of a subroutine also # renders what is returned by default, although # sort routines even more magical than that! }

Replies are listed 'Best First'.
Re^2: Print not printing
by brian_d_foy (Abbot) on Jun 24, 2005 at 16:17 UTC

    $a and $b aren't that special. The sort built-in uses their package versions (try the code below in main:: to see if it still works), but that's as magical as they get. They otherwise act like any other package variable, and you don't have to be afraid of them. I'd stay away from them because they aren't descriptive variable names.

    #!/usr/bin/perl -l package Foo; $, = " "; print sort { $Foo::a <=> $Foo::b } qw( 1 7 2 0 4 3 6 );

    In your sort call within the foreach, you don't need an argument. :)

    --
    brian d foy <brian@stonehenge.com>
      Well, they're more special than "the variables sort() happens to use". To achieve that handy usage without warnings, Perl exempts $a and $b from declaration checks under strict vars. That means that

      perl -we'use strict; $a = 5; print $a'

      compiles and runs without errors, while

      perl -we'use strict; $c = 5; print $c'

      won't even compile.

      This has bitten me in real life when trying to cut down a test case for closure scoping behavior. My real code was doing different things than my one-liners, and there was NO DIFFERENCE except the variable names. I was tearing my hair out.

      $a and $b are naturals for quick throwaway code; the documentation uses them in examples all over the place. However, $c and $d are much better choices. I find myself completely avoiding $a and $b outside of sort(), just to be on the safe side.

      It's true that $a and $b will work normally; but I suppose I have the philosophy that code should be as self-evident as possible and using $a and $b as ordinary variables is apt to confuse the reader/maintainer.

      -S

      One world, one people