|
1 |
#!
/usr/local/bin/perl5 # file two |
|
2 |
print "What is your name?\n"; |
|
3 |
$name =
<STDIN>; |
|
4 |
print "Hello
$name"; |
Comments:
$name
Variables begin with the $ (Mnemonic aid: scalar variables. A scalar is a single number in a matrix, hence the dollar sign to remind you of a scalar.) Variables can hold numbers or strings. Note that variable names are case sensitive. Hence: $name is not the same variable as $Name and both of these differ from $NAME, etc.
=
The single equals sign is the assignment operator:
$odd_number = 3; assigns the number three to the variable $odd_number
$odd_number_label = “odd”; assigns a string to a variable
Equality or inequality is tested with different operators depending whether the information is numeric or string:
$odd_number == 4; false: this is a test of equality for numbers
$odd_number != 3; false: this is a test of inequality for numbers
$odd_number_label eq “even” false: this is a test of equality for strings
$odd_number_label ne “odd” false: this is a test of inequality for strings
STDIN
The standard input file handle; that is, input from the keyboard. Evaluating a filehandle in angle brackets yields the next line from that file.
STDOUT The standard output filehandle.
It is possible to use specific files for input and output.
Consider the following program that opens a file “in_stuff” and writes the contents to “out_stuff”.
#! /usr/local/bin/perl5
open(IN, "in_stuff"); # filehandle IN for input
open(OUT, ">out_stuff"); # filehandle OUT for output
while (<IN>) { print OUT $_; }
close(IN);
close(OUT);
Note the use of the > to pipe the contents into the file “out_stuff”.