Make sure you’ve downloaded the sample data, and then create the following text file:
#!/usr/bin/perl
while (<>) {
print;
}
Save this file as the filename show. Once you’ve saved it, make sure that it is executable by you. Go to your command line, make sure that your are in the correct folder, and type:
chmod u+x show
On Mac OS X, you can ensure that you are in the correct folder by typing “cd” in the terminal, a space, and then dragging the folder onto your terminal window. Press return, and you will change directory into that folder.
Now, type:
./show show
The script should show you itself. Make sure that songs.txt is in the same directory as your script, and type:
./show songs.txt
The show script should show you all 7,006 lines in the songs.txt file.
- What is it doing?
- This is about as simple of a Perl script as you can get. While it doesn’t do much yet, this is a shell around which you can build quite a few useful scripts.
- Indentation
- In the above script, the print command is indented by one tab. Indentation makes it much easier to read your scripts. It is much easier to see where where blocks and other blocks begin and end if those blocks are indented. While Perl does not care about indentation, it is for all practical purposes required that you indent; if you have blocks inside of blocks, those will be indented further.
- Basic regular expressions
- Our current script is a filter. It takes some raw data on one end, filters it, and produces modified data on the other end. You can also think of a filter as a sausage grinder. Our filter, however, is a very leaky sieve: it currently lets everything through.
- Splitting and printing
- Our search is working nicely, but it is returning a lot more information than we really need. The data file contains quite a bit of information about our songs. It’d be nice to display it in a more useful form. To do this, we first need to break it up into its pieces.
- The basic Perl filter: Comments
- I mentioned earlier that the pound sign at the beginning of a line causes Perl to completely ignore that line. This makes the pound sign a useful way of adding comments to your scripts. Comments are very important: they help you remember what you meant by this snippet of script several months or even years later when you look at the script again.