![]() |
Shortcuts in Perl
IntroductionPerl is renowned for being a language where you can express complicated commands in a very small amount of space. We'll start with the simplest of programs, which simply reads in characters from the keyboard and repeats them back to the console. In Perl you might write this like so: Code: Perl
You may think that this program is already as short as it can be, but through using Perl's special variables, we can make it shorter: The default scalar variable: $_Perl has a number of special variables that are automatically assigned in the general course of a program, they can be used to access information about the program itself, such as the name or process id, the command line arguments, or the results of the last regular expression. The most general, and maybe the most useful of these special variables is $_, the default variable. The default variable is where the results of some Perl constructs and functions are put if you don't specify an assignment, and is used as the argument to certain functions if none is given. This sounds vague and can be confusing until you're familiar with it, but it can also be powerful. We can use $_ to eliminate the need for the variable $line in our program: Code: Perl
Code: P
Code: Perl
This is fine if we just want to mirror STDIN to STDOUT, but what if we'd like our program to act more like the Unix filter cat, which can open and print files as well. Now we could check the command line arguments and test to see if they're valid files, open and print them in order, but since this is such a common thing to do Perl has an easier (and shorter!) way. The special file handle: <>Like the default variable, the special file handle -- written as <> is a short cut in the language added to make programs easier to write. The special file handle treats all command line arguments as file names, and opens each in turn. If there are no command line arguments then it opens and reads from STDIN. As per the UNIX convention, if "-" is given as a command line argument it opens STDIN in place of a file. So if we wanted to write a version of the above program that could support files given on the command line it would be as simple as: Code: Perl
Counting Line Numbers If we want to process the lines of the input individually then it's not enough to just link the file handle to print, let's take a look at a simple program to add line numbers to the lines of input: Code: Perl
Even with these simple programs, it's easy to see how using special variables can make your programs smaller and faster to write. If you're interested, information about all of Perl's special variables can be found in the perlvar section of the Perl manual (http://perldoc.perl.org/perlvar.html). |
Re: Shortcuts in Perl
My first post in this site ;)
For most of the cases you can use the variable $. So the code would come: Code:
while (<>) { |
| All times are GMT +5.5. The time now is 02:56. |