home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam    

Book HomeLearning Perl, 3rd EditionSearch this book

3.7. Perl's Favorite Default: $_

If you omit the control variable from the beginning of the foreach loop, Perl uses its favorite default variable, $_. This is (mostly) just like any other scalar variable, except for its unusual name. For example:

foreach (1..10) {  # Uses $_ by default
  print "I can count to $_!\n";

Although this isn't Perl's only default by a long shot, it's Perl's most common default. We'll see many other cases in which Perl will automatically use $_ when you don't tell it to use some other variable or value, thereby saving the programmer from the heavy labor of having to think up and type a new variable name. So as not to keep you in suspense, one of those cases is print, which will print $_ if given no other argument:

$_ = "Yabba dabba doo\n";
print;  # prints $_ by default

3.7.2. The sort Operator

The sort operator takes a list of values (which may come from an array) and sorts them in the internal character ordering. For ASCII strings, that would be ASCIIbetical order. Of course, ASCII is a strange place where all of the capital letters come before all of the lowercase letters, where the numbers come before the letters, and the punctuation marks -- well, those are here, there, and everywhere. But sorting in ASCII order is just the default behavior; we'll see in Chapter 15, "Strings and Sorting", Strings and Sorting, how to sort in whatever order you'd like:

@rocks = qw/ bedrock slate rubble granite /;
@sorted = sort(@rocks);      # gets bedrock, granite, rubble, slate
@back = reverse sort @rocks; # these go from slate to bedrock
@rocks = sort @rocks;        # puts sorted result back into @rocks
@numbers = sort 97..102;     # gets 100, 101, 102, 97, 98, 99

As you can see from that last example, sorting numbers as if they were strings may not give useful results. But, of course, any string that starts with 1 has to sort before any string that starts with 9, according to the default sorting rules. And like what happened with reverse, the arguments themselves aren't affected. If you want to sort an array, you must store the result back into that array:

sort @rocks;          # WRONG, doesn't modify @rocks
@rocks = sort @rocks; # Now the rock collection is in order

Library Navigation Links

Copyright © 2002 O'Reilly & Associates. All rights reserved.