To execute the perl script copy the blue text from the screen
and paste it into a file. Save the file, for example, under the
name "hello". Then type at the Unix prompt:
perl hello
Explanations
# | indicates a comment; the line is ignored |
a command; prints the string between the quotes | |
\n | newline character |
; | indicates the end of a command |
Exercises
1) Add a second print statement to the script from the example. (For example print "How are you?".) What does adding or deleting "\n" change?
2) Make some random changes, for example, delete the "#" before "This program says ..."; delete the semicolon after "World\n"; etc. In most cases you will get an error message. The only useful piece of information in that message is probably the number of the line in which the error occurred. Fix the errors until the script executes again successfully.
3) Type "perl -v" at the command line. It gives you information
about the specific version of Perl that is installed on the computer.
Type "man perl" at the command line. It provides you with on-line
help. (Don't try to read it right now - it's too technical. Just
keep in mind that it's there in case you need it later in the semester.)
To exit "man perl" type "q" or Ctrl-c.
Explanations
$name | a variable for a "name" |
= | an assignment operator |
<STDIN> | reads from standard input (i.e. keyboard) |
chomp | deletes the newline character ("enter" key) |
Exercises:
1) What happens if you delete the line with "chomp"?
2) Write a program that
asks two people for their names; stores the names in variables
called $name1 and $name2; says hello to both of them.
Exercises
1) Execute the script. Make sure you understand every line.
2) What is the value of $a and $b after each of the following
statements?
$a=5; $b=10;
$a++;
$b--;$b--;$b++;
$a = $a + $b;
$b = $a;
$a--;
3) Write a script that asks a user for a number. The script
adds 3 to that number. Then multiplies the result by 2, subtracts 4,
subtracts twice the original number, adds 3, then prints
the result.
chmod u+x program_name
and then execute it by simply typing the program_name.