Perl Basics - Part 1
I don't believe in fidgeting around. Here's a very simple Perl script:
#!/usr/local/bin/perl # 1
$name="Foo";
$friends=1; #I only have one friend
#$friends=2; #actually, I have 2 friends
#$friends="many";#I have too many friends to count # 5
if ($friends == 1)
{
print "$name, you are my best friend.";
}
elsif ($friends > 1 && $friends < 3) #10
{
print "$name, you are one of my best friends.";
}
elsif ($friends eq "many")
{ #15
print "You're swell.";
}
else
{
print "I'm confused"; #20
}
So what does this tell us about Perl?
- You need to tell the script where Perl is.
- In the first line, #!/usr/local/bin/perl, everything after the
#! represents the full path to the actual Perl executable. This will be
different on different machines. You might be able to locate it by typing whereis
perl, or you might have to ask a sysadmin. If you don't have Perl on your
system, then you're pretty much out of luck as far as this lesson goes.
- Variable names start with $.
- $name is a variable set at line 2 with the = sign to "Foo".
- Commands end with a semicolon.
- This is very important and until you have quite a bit of experience will
probably be the greatest source of bugs in your programs. Perl doesn't care about
whitespace (line breaks, tabs, spaces, etc.), so you need to tell it yourself where one
command ends and the next begins.
- # "comments out" lines.
- Anything between a # and the next carriage return is ignored by Perl.
- Things you test as conditionals (e.g., in if statements) need to
be put in parantheses.
- See line 6. Notice also that you don't need a semicolon in the conditional
since it's not actually a command.
- Things to do if a conditional is true need to be put in curly
brackets.
- Commands inside the curly brackets need to be semi-coloned like any other
commands. Indentation, while unnecessary, improves readability and makes the
likelihood of losing your place in a multiple conditional (if statement inside an if
statement, etc.).
- You can generally put variable names inside regular double-quoted
strings.
- In lines 8 and 12, the $name variable is treated no differently from
any other text in the print statement, yet will be interpreted (here as Foo)
inside the double quotes.
- elsif
- You don't need to make an else with a sub-if.
- && and ||
- logical and and or work inside conditionals.
- testing numbers vs testing strings
- Notice in line 6 that we used == to test numerical equality and in line
14 we used eq to test string equality. = always sets variables rather
than testing them, even inside conditional ()'s, so look out for it. (The opposite of
== is !=, the opposite of eq is ne.)
- print defaults to STDOUT
- For those of you who took my Unix crash course, I told you we were going to
need this later. We still will.
"That was easy! I want more!"
"Hang on a sec... Let me try it again from the top