tags:

views:

297

answers:

6

First off, does anyone have a comprehensive list of the Perl special variables?

Second, are there any tasks that are much easier using them? I always unset $/ to read in files all at once, and $| to automatically flush buffers, but I'm not sure of any others.

And third, should one use the Perl special variables, or be more explicit in their coding. Personally I'm a fan of using the special variables to manipulate the way code behaves, but I've heard others argue that it just confuses things.

+17  A: 

They are all documented in perlvar.

Note that the long names are only usable if you use English qw( -no_match_vars ); first.

R. Bemrose
+1 Sometimes they can be confusing, but I'm never more than 3 seconds away from the answer.
Chris Lutz
+4  A: 

The three I use the most are $_, @_ and $!.

I like to use $_ when looping through an array, retrieving parameters (as pointed out by Motti, this is actually @_) or performing substitutions:

Example 1.1:

foreach (@items)
{
  print $_;
}

Example 1.2:

my $prm1 = shift; # implicit use of @_ or @ARGV depending on context

Example 1.3:

s/" "/""/ig; # implicit use of $_

I use $! in cases like this:

Example 2.1:

open(FILE, ">>myfile") || die "Error: $!";

I do agree though, it makes the code more confusing to someone not familiar with Perl. But confusing other people is one of the joys of knowing the language! :)

cakeforcerberus
Personally, I hate using $_ and prefer to avoid it whenever possible (such as foreach my $item (@items) ), but $! is definitely useful.
R. Bemrose
I'm a big fan of `$_`, and use it all the time.
Justin
Check out the three argument form of open with lexical filehandles: `open my $file_handle, '>>', 'myfile' or die "Fiery death while trying to open [myfile]: $!"`
Telemachus
`shift` with no arguments does an implicit shift of `@_`, not `$_`
friedo
I really only use `$_`, when it improves my code to do so.
Brad Gilbert
My rule of thumb, if I ever have to type $_ I shouldn't be using it (pedants will note the map/grep exception). Also it really shouldn't be expected to survive more than a statement or two, too much opportunity for something blowing it away.
Schwern
$_ is useful if you have a whole list of regexs that you want to match against the same thing.
Inshallah
your example with `shift` doesn't use `$_`, it uses `@_` (in functions) or `@ARGV` (out of functions).
Motti
If you don't also use `$@` you aren't really a good Perl programmer.
Brad Gilbert
@Brad Gilbert - I never claimed to be one.
cakeforcerberus
@Motti: Thanks for the correction. I guess I use more Perl special variables than I thought. :) I corrected my answer.
cakeforcerberus
+2  A: 

Typical ones I use are $_, @_, @ARGV, $!, $/. Other ones I comment heavily.

Brad notes that $@ is also a pretty common variable. (Error value from eval()).

Paul Nathan
I would add `$@` to the list.
Brad Gilbert
+7  A: 

Always remember to local'ize your changes to the punctuation variables. Some of the punctuation variables are useful, others should not be used. For instance, $[ should never be used (it changes the base index of arrays, so local $[ = 1; will cause 1 to refer to the first item in a list or array). Others like $" are iffy. You have to balance the usefulness of not having to do the join manually. For instance, which of these is easier to understand?

local $" = " :: ";               #"
my $s = "@a / @b / @c\n";

versus

my $sep = " :: ";
my $s = join(" / ", join($sep, @a), join($sep, @a), join($sep, @a)) . "\n";

or

my $s = join(" / ", map { join " :: ", @$_ }, \(@a, @b, @c)) . "\n";
Chas. Owens
A: 

I say use them--if you're using Perl, you're obviously not choosing it for neophyte readability. Any more-than-casual developer will likely have a browser/reference window open, and sifting through the perlvar manpage in one window is likely no less arduous than looking up definitions of (and assignments to!) global or external variables. As an example, I just recently encountered the new-in-5.10.x named capture buffers:

/^(?<myName>.*)$/;
# and later
my $capture = %+{'myName'};

And figuring out what was going on wasn't any harder than going into parlvar/perlre and reading a little bit.

I'd much rather find a bunch of wacky special vars in undocumented code than a bunch of wacky algorithms in undocumented code.

Marc Bollinger
+4  A: 

1) As far as which ones I use often:

  • $! is quintessential for IO error handling

  • $@ for eval error handling when calling mis-designed libraries (like database ones) whose coders weren't considerate enough to code in decent error handling other than "die"

  • $_ for map/grep blocks, although I 100% agree with a poster above that using it for regular code is not a good practice.

  • $| for flushing buffers

2) As far as using punctuation vs. English names, I'll pick on Marc Bollinger's reply above although the same rebuttal goes for anyone arguing that there's no benefit to using English names.

"if you're using Perl, you're obviously not choosing it for neophyte readability"

Marc, I find that is not always (or rather almost never) true. Then again, 99% of my Perl experience is writing production Perl code for large companies, 90% of it full fledged applications instead of 10-line hack scripts, so my analysis may not apply in other domains. The reasons such thinking as Marc's is wrong are:

  • Just because I'm a Perl non-neophyte (to put it mildly), some noob analyst hired a year ago - or an outsourced "genius" in Mumbai - is probably not. You may not want to confuse them any more than they already are. "If code was hard to write, it should be hard to read" is not exactly high on the list of good attitudes of professional developers, in any language.

  • When I'm up at 2am, half-asleep and troubleshooting a production problem, I really do not want to depend on the ability of my already-nearly-blind eyes to distinguish between $! and $|. Especially in a code written by before mentioned Mumbai "genius" who may not have known which one of them to use and switched them around.

  • When I'm reading a code left unfinished by a guy who was cough "restructured" cough out of the company a year ago, I'd rather concentrate on intricacies of screwy logic than readability of the punctuation soup.

DVK
Can we stop the Mumbai-baiting, perhaps? Thanks.
Telemachus
I believe it is called realism. Vast majority of members of an outsourcing team are neither expert at anything, nor good coders. If they were (or are), they would not be working at low-paying IT outsourcing outfits. Having worked with such "help" myself over the years many times, I (and many many other people in IT I know) have yet to see any exceptions to prove that what I said was "baiting" as opposed to bitter truth. I've nothing to do with programmers in Mumbai in general, only the TCS and such drones.
DVK