in reply to Re: Print not printing
in thread Print not printing

$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>

Replies are listed 'Best First'.
Re^3: Print not printing
by mrpeabody (Friar) on Jun 24, 2005 at 19:20 UTC
    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.

Re^3: Print not printing
by anonymized user 468275 (Curate) on Jun 27, 2005 at 10:01 UTC
    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