![]() |
|
laziness, impatience, and hubris | |
PerlMonks |
Perl White Magic - Special Variables and Command Line Switchesby cog (Parson) |
on Feb 16, 2005 at 10:55 UTC ( #431511=perltutorial: print w/replies, xml ) | Need Help?? |
ContextThis tutorial on Special Variables and Command Line Switches was originally published in the YAPC::EU::2004 proceedings (where it was awarded the prize for best paper).PrologueEverything was silent, but for the two of them breathing.- 'All my life I've felt there was more to system administration than this... And now... now that you've arrived... now I know I was right!' - 'You really think I'll be up to the job, Command Line?' - 'Yes, you will. You will, $_.' Super-powers come to those who wait$_ woke up with a sudden and loud noise. It would have sounded like a fan, should he know what a fan was.He knew there were things to be done, and that sooner or later he would be called into aid. He did not know, however, what those particular things were and who would be in charge of choosing how and what to do exactly. As soon as these thoughts crossed his mind, gravity suddenly disappeared. Some kind of magnet picked him up and promptly took him to the top of a script, right after a shebang. Beneath him, comments could be seen. Commented code can mean an awfull lot of different things, and $_ knew this better than any other variable. It can be meant to identify the Creator or the purpose of life, but can also exist just to state that something is yet unfinished. One would hope it was not the case... Slowly at first, he started going down the script. Slowly enough to read the comments: # counts words and lines in a file He passed that line and saw the next following ones:
Not knowing what to do, he started feeling anxious as gravity pulled him nearer to his destiny. At this point, Command Line shouted at him: - 'Use the monitor on your wrist!!' He looked at his wrist and saw something that resembled a smaller version of
something someone wanting to hitchhike through the galaxy would take as a guide,
but it was actually something someone wanting to hitchhiking through a Perl
script would take as a guide. Plus, it had no "Don't Panic" stuff; instead, it
had Perldoc written on it.
- 'Hi', said $_.
So he did, and promptly understood what a special variable was: they were
there, they just couldn't be seen... $., in particular, had been
counting the input lines right from the beginning of the script, and was ready
to pop into action when called... and so it did.
- 'How do you feel?'
Different perspectivesAs before, $_ was taken again by the strange force. He was ready for it before it started, but then came the surprise...Strangely enough, this time he wasn't moving vertically, but rather horizontally... Everything resembled an assembly line. The first thing he noticed was a command line switch, but he did not know what one was yet. He reached the monitor on his wrist and started hitting it desperately. He eventually strolled across perlrun and searched for it. He found it:
That explained the horizontal movement.
perl -e 'while (<>) {$w += split /\W+/} print "$. $w\n"' He could now understand what was going on. This was practically the same script
as before, except now it wasn't a script anymore, it was an "One-Liner", one of
the most beautiful creations by the hand and mind of the Original
Creator (The one and only: Larry Wall).
-ne was surely the same as -n -e, and he already knew one of them. He looked for the other and promptly found it:
He looked at the rest of the line to get a better feel of what was going on: perl -ne '$w+=split /\W+/; END{print"$w $.\n"}' Everything seemed OK now. He already knew that any END block was to be executed only at the end of the script, after everything else. The program would go like this:
That was rather close to his first task, but with less coding going around.
Someone was obviously doing experiments, but that was good for him, as he was
surely learning from it.
A whole bag of switchesAgain, the same startup routine. This time, the user was noticeably more experienced:
At least he seemed to know what he was doing. Every good script should start with something like that. The Perldoc screen told him: -w prints warnings about dubious constructs One should always use it.
#Adding a commit each 100 lines He had heard something about this... DBA's sometimes have trouble
inserting too many rows in a table, as that very same information is kept as
roolback data between commit instructions
(so everything can be undone, if needed).
It wasn't as complicated as it would seem at first. He noticed the $line
part could be replaced with $., and the rest of the code could be
shortened with the -n, but he really wasn't expecting what happened in
his next task.
He looked up for -p:
- 'So that's why the print statement has been removed.' It simply wasn't needed anymore, as the -p switch would do the same as
-n and also print each line.
perl -i -pe 'print "commit;\n" unless ($.%100)' He knew what to do:
- 'Wow.' He couldn't help the remark. That meant the input was to be read, processed, and then rewritten over the
original file. This would probably save the user the trouble of copying a new
file over an older one.
They come in pairsThe same routine. Once again, $_ was ready for surprises and had his Perldoc prepared.
He looked up -l and, to his surprise, he found the exact code he was running on. Hum... the user probably had a Perldoc of his own... (Perhaps he was a special variable too?) The text on -l would go:
After reading a little bit more, he understood what was going on: the trailing "\n" on each line would be discarded, each line would be trimmed up to 80 chars and printed with the "\n" back on. He noticed the text mentioned two other variables: $/ and $\... and their names sounded fierce. Usually, one goes from more code to less code, and not the other way around, but this was exactly what happened next. His next script, instead of using the -l switch, seemed to do the same by using those very same two variables. The user was obviously up to something (probably just testing and learning new features).
Dazzled in astonishment, he didn't even think about reaching for his Perldoc. He instead asked the variables directly what they were up to. - 'Hi.
As good as the conversation was getting, $_ noticed the end of the script arriving. - 'What's the purpose of what you're doing?'
So that was the name of this magnet: EOF. The mighty variable$_ fell asleep with $/ on his head, and woke up still thinking about it.He was called into action and, to his contentment, there was $/:
- 'Hi.'
That night, $_ had trouble falling asleep, dreaming of the possibilities those $/'s tricks could mean. SeparationsYet another day.perl -ane 'print shift(@F), "\n"' Everything was so easy now that he was used to Perldoc. He was even able to open two windows at a time, one with perlrun and another with perlvar. He used the first one to search for -a:
and the second for @F:
To tell the truth, the entry for -a already explained what @F was
doing there. Anyway, the code in the documentation was very similar to the one
he was running on. He was clearly on a script for printing the first word of
every input line. What for? He would soon find out.
This was a very simple way of studying how often commands are ran on the
system.
An alternate delimiter may be specified using -F. Another switch. And soon he would see and example of its usage: perl -F: -ane 'print shift(@F),"\n"' Hum... this would split the input lines on ':' and print every first element of those lines. (Maybe it would run on /etc/passwd, for a list of users) TIMTOWTDICommand Line approached $_ softly and woke him gently: - 'Wake up, $_!'
They walked along for a while. - 'So what's this lesson I'm going to learn?'
$_ went through it as if he hadn't been doing anything else all his life. - 'There.' - 'Very good. Did you notice the output?' 1 2 3 4 5 - 'Cool...', said $_, 'Perl already knows he has to put a space between
those elements, right?'
- 'Done!'
1|2|3|4|5 - 'Yes. I assume Perl takes the contents of $" and prints that everytime
an array is printed. Right?'
$_ went through it. - 'Now look at the output produced.' 12345 - 'Odd... shouldn't a space be there too, separating elements?'
- 'And now the output!' 1-2-3-4-5 - 'See?'
$_ was clever enough to remain silent for a while and think about what Command Line had just said... "There's more than one way to do it!" Thoughts'I like it here.' exclaimed $_. 'All these switches and special variables, being famous and loved by all.' - 'That's not entirely true... Some variables are not very well known, and
others are not very appreciated.' replied Command Line.
Modules and one-liners$_ was on the move again.
He looked -M on Perldoc and was preparing to look for -E too when he
noticed there was no need for that...
The E was actually the beginning of a parameter for the -M
switch.
The sky is the limit'I think I'm getting the hang of this.'- 'There is still much to learn, $_.' - 'Are there more special variables?' - 'Quite a few. And some more command line switches, too.' - 'Wow... This is just amazing...' - 'I'm glad you like it. However, we won't have the time to go through all of them now.' - 'Oh... That's too bad...' - 'Don't worry. There are lots of places where you can learn more, and Perldoc is one of them.' $_ stared at his Perldoc. - 'And besides that, you have lots of mailing lists, perlmonks, etc. You'll never run out of information. The trick is to keep practising.' $_ smiled. Revelations$_ was browsing his Perldoc and talking to Command Line:- 'Perl really seems to be a wonderful language, and all the special variables and command line switches take an important part in it.' - 'Yes, but there is much more than that to Perl.' - 'Really?' - 'Yep. You should wait to read some of the other articles the author of this one is thinking of writing.' - 'Wow... I can see why the user chose Perl.' - 'Yes, but it wasn't like that in the beginning.' - 'Really?' - 'Really. Things were a lot different, until the moment he had an epiphany, and heard a voice saying: "Don't try to do everything with the Bash. Instead, only try to realize the truth."' - 'What truth?' - 'There is no Bash.'
Back to
Tutorials
|
|