Now that you've got the basics of the language down, this secondarticle in the series teaches you about Perl's variables and operators, andalso introduces you to conditional expressions.
Thus far, you've been assigning values to your variables at the time of writing the program itself [referred to in geek lingo as "design time"]. In the real world, however, many variables are assigned only after the program is executed [referred to as "run time"]. And so, this next program allows you to ask the user for input, assign this input to a variable, and then perform specific actions on that variable.
#!/usr/bin/perl
# ask a question...
print "Gimme a number! ";
# get an answer...
$number = <STDIN>;
# process the answer...
chomp($number);
$square = $number * $number;
# display the result
print "The square of $number is $square\n";
If you try it out, you'll see something like this:
Gimme a number! 4
The square of 4 is 16
Let's go through this in detail. The first line of the
program prints a prompt, asking the user to enter a number. Once the user enters a number, that input is assigned to the variable $number via the <STDIN> file handler. This particular file handler allows you to access data entered by the user at the command prompt, also referred to as STanDard INput.
At this point in time, the variable $number contains the data entered by you at the prompt, together with a newline [\n] character [caused by you hitting the Enter key]. Before the number can be processed, it is important that you remove the newline character, as leaving it in could adversely affect the rest of your program. Hence, chomp().
The chomp() function's sole purpose is to remove the newline character from the end of a variable, if it exists. Once that's taken care of, the number is multiplied by itself, and the result is displayed. Note our slightly modified usage of the print() function in this example - instead of using parentheses, we're simply printing a string and replacing the variables in it with their actual values.