Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re^3: referencing list

by sauoq (Abbot)
on Jun 06, 2012 at 10:50 UTC ( [id://974688]=note: print w/replies, xml ) Need Help??


in reply to Re^2: referencing list
in thread referencing list

However if I add 'use strict;', I get the message 'Global symbol "$c" requires explicit package name ...'.

Yes, and if you named $a and $b something more reasonable, you'd hear about them too. (You only don't because they are special case variables used in sort blocks.) You can take care of that by declaring your globals though, and that's something you should be doing anyway. The following is safe under warnings and strict.

use warnings; use strict; my @x = (1,2,3); our ($a,$b,$c); (*a,*b,*c) = \(@x); $a = "f"; $b = "o"; $c = "o"; print sort {$b<=>$a} qw(17 11 13 29 31 37 3 2 7 5 19 23); print @x;
It also shows that using $a and $b is fine, despite also using them for a sort block. The problem with using $a and $b comes up when you have them declared as lexicals...
$ perl -le 'my $a=1; print sort {$b<=>$a} 1' Can't use "my $a" in sort comparison at -e line 1.
Since we all usually declare our variables as lexicals these days, the advice "don't use $a and $b" get dispensed without a lot of understanding about why it matters. Or when it doesn't.

Update: By the way, Data::Alias is a fine module and you shouldn't hesitate to use it if you can and it passes its tests. Sometimes people don't have control over what perl modules are available in their environment, particularly ones with an XS component. And sometimes modules have bugs, particularly platform specific ones, that prevent them being used. And sometimes adding a module isn't worth it when a couple extra lines of code will do. This is why I offered the old way of doing this. It's up to you to decide what is most appropriate in your situation.

-sauoq
"My two cents aren't worth a dime.";

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others browsing the Monastery: (3)
As of 2024-04-19 00:49 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found