Vous êtes sur la page 1sur 8

Activity 2: Scalar Data

Objectives:
Thorough understanding of Perl programming Learn the general things to take note as a beginning Perl programmer work with variables Understand scalar data Have a background on strict, warnings and diagnostics in Perl

Concepts
In programming, you usually take some data and do something with it. When you have data in your program, you tend to store it in a variable, a named entity that contains the data. Variables are the little beasties everyone should be familiar with. As you program, many of your errors will be the wrong data in the wrong variable. The simplest kind of data that Perl manipulates is a scalar. Most scalars are either a number or a string of characters. Perl treats them almost the same even though strings and numbers are entirely different in nature. A scalar value can be acted upon with operators (like addition or concatenation), generally yielding a scalar result. A scalar value can be stored into a scalar variable. Scalars can be read from files and devices and can be written out as well.

Subject Perl Script

The my Function
Each variable in the preceding code is declared with the my function. The my function in Perl is the most common way to declare a variable and it makes the variable visible only to the current scope to hide it from other parts of your program. Thats important to ensure that a distant part of your program does not silently change your data. That kind of self-inflicted bug is too easy to create and extremely difficult to find and fix.

Sigils
You see the punctuation before each variable name the dollar sign ( $ ) as shown below:
my $name = Gel;

In Perl, this leading punctuation is called a sigil. A sigil is a punctuation symbol that tells you about the variable you use. When you see a variable beginning with a dollar sign, you should know that you are accessing a $calar value.

Perls Built-in Warnings


Perl has the ability to warn you when it detects something suspicious going on in your program. To run your program with warnings turned on, use the w option on the command line.
$ perl w perl_script

You can turn on warnings on the #! line


#!/usr/bin/perl -w

With Perl 5.6 and later, you can turn on warnings with a pragma but be careful because it will not work on earlier versions of Perl.
#!/usr/bin/perl use warnings;

Take note that warnings are generally meant for programmers, not for end users. If you get a warning message you do not understand, you can get a longer description of the problem with the diagnostics pragma.
#!/usr/bin/perl use diagnostics;

When you placed the use diagnostics pragma to your program, it may seem to you that your program now pauses for a moment whenever you launch it. This is due to the fact that your program has to do a lot of work (and a lot of memory space to consume) just in case you want to read the documentation as soon as Perl notices your mistakes, if any. If would be better to correct your program to avoid causing the warnings rather than removing the use diagnostics pragma. A further optimization can be had by using one of Perls command-line options, -M to load the pragma only when needed instead of editing the source code each time to enable and disable diagnostics
$ perl Mdiagnostics ./perl_script

Scalars
In Perl, a scalar is merely a single value. Table 2.1.
my $age = 40; my $nick_name = E-Mac;

A scalar can be a number, string or a reference; scalar means a single value; In the example shown above: my is afunction declaring the variable $age and $nick_name are the variables = is the assignment operator 40 is the numeric literal assigned to $age and E-Mac is the string literal assigned to $nick_name Table 2.2.
my $var; # value of $var is undef

If you do not assign anything to a variable, it has a special value called undef. You can also declare several scalars at once by putting parentheses around them.
my ($age, $nick_name);

To assign values to them when you declare them by putting parentheses around the right side:
my ($age, $nick_name) = (40, E-Mac);

Strings
Assigning a string to a scalar is simple.
my $instructor = Ms. Gel; my $wife = Chkiz;

Both of the lines shown above are valid ways to assign a string to a scalar. When using single quotes, what you see inside of the quotes is generally exactly what you get. However, when you use double quotes, you can use escape characters and interpolate other variables in the string. Table 2.3.
my $instructor = Ms. Gel; my $wife = Chkiz; my $string = My $instructor and $wife are cousins\n;

Quotes and Quote Operators Sometimes, though, you must interpolate something and use double quotes at the same time as shown below:
my $reviewer = Ana Paula; my $review = $reviewer wrote \This book is awful\;

This can be very confusing to read, so Perl provides rich quotelike-operators. The q{ } replaces single quotes and qq{ } replaces double-quotes. This can eliminate much painful escaping.

my $reviewer = Ana Paula; my $review = qq{$reviewer wrote this book is awesome};

To use quote operators over multiple lines, we utilize the here-docs. These types of strings require a << followed by a string literal of your choosing. All following text will be included in the string until the string literal is found again: Table 2.4.
my $letter = <<END_APOLOGY; Dear $manager, Im very sorry for not completing the job you assigned me. I will do my best to finish them at the soonest possible time. Sincerely, E-Mac END_APOLOGY

. Operator You can concatenate or join string values with the . (dot) operator.
hello . world hello . ' ' . world # same as 'helloworld' # same as 'hello world'

Numbers
Lot of work for a programmer will deal with numbers such as integers, floating point numbers. Integer and Floats Scalar can hold numbers. Just assign the number to them:
my $answer = 40; my $body_temp_fah = 98.6;

Mathematical operations As with any other programming language, we can perform mathematical operations on numbers with Perl.

Example 2:

Comparison Operators (Strings and Numbers) Comparison Equal Not Equal Less Than Greater Than Less Than or equal to Greater than or equal to Numeric == != < > <= >= String eq ne lt gt le ge

Example Expressions
35 != 30 + 5 35 == 35.0 '35' eq '35.0' 'fred' lt 'barney' 'fred' lt 'free' 'fred' eq fred 'fred' eq 'Fred' ' ' gt '' # # # # # # # # false true false (comparison of strings) false true true false true

The if Control Structure


Based upon the result of the comparison, you most probably want your program to make a decision. Like other programming languages, Perl has an if control structure that only executes if it condition returns a true value.
if ($name gt 'Gel'){ print '$name comes after 'E-Mac' in sorted order.\n; }

If you need an alternative choice, the else keyword provide that as well:
if ($name gt 'Gel'){ print '$name comes after 'E-Mac' in sorted order.\n; } else { print '$name' does not come after 'E-Mac'.\n; print Maybe it is the same string, in fact.\n; }

Boolean Values Perl does not have a separate Boolean data type like some languages have. How do you think Perl decides whether a given value is true or false? Perl uses a few simple rules: If the value is a number, 0 mean false; all other numbers mean true Otherwise, if the value is a string, the empty string ('') means false; all other strings mean true Otherwise (that is, if the value is another kind of scalar than a number or a string) convert it to a number or a string and try again.

Note: The string '0' is the exact same scalar value as the number 0, Perl has to treat them both the same. That means that the string '0' is the only non-empty string that is false. If you need to get the opposite of any Boolean value, use the unary not operator ( ! ). If what follows is a true value, it returns false; if what follows is false, it returns true:
if (! $is_bigger ){ # Do something when $is_bigger is not true }

Getting User Input


The simplest way to get a value from the keyboard into a Perl program is by using the line-input operator, <STDIN>. Each time you use <STDIN> in a place where Perl expects a scalar value, Perl reads the next complete text line from the standard input (up to the first newline) and uses that string as the value of <STDIN>. Standard input can mean many things but unless you do something uncommon, it will always mean the

keyboard of the user who invoked your program. If there's nothing waiting for <STDIN> to read, the Perl program will stop and wait for you to enter some characters followed by a newline (return). Example3:

The chomp Operator


chomp operator works on a variable that holds a string value and that string should end in a newline character. chomp( ) removes the newline. Thats all it does.
$text = a line of text\n; chomp($text); # or the same thing from <STDIN> # Gets rid of the newline character

As you develop your programming skills in Perl, you will find out that chomp is useful that you will put it into nearly every program you write. You may also write chomp( ) with or without the parentheses.

The while Control Structure


Like most algorithmic programming languages, Perl has a number of looping structures. One of them is the while loop. The while loop repeats a block of code as ling as a condition is true: Example 4:

As always in Perl, the truth value here works like the truth value in the if test. The conditional expression is evaluated before the first iteration, so the loop may be skipped completely if the condition is initially false. The defined Function One operator that can return undef is the line-input operator, <STDIN>. Normally, it will return a line of text. But if there is no more input, such as at end-of-file, it returns undef to signal this. To tell whether a value is undef and not the empty string, use the defined function, which returns false for undef and true for everything else. Example 5:

Activity Exercises:
1. Write a program that computes the circumference of a circle with a radius of 12.5. Circumference is 2 pi times the radius (2 x 3.14.1592654). The answer you should get should be about 78.5. 2. Create another program by modifying the previous item to prompt for and accept a radius from the person running the program. So if the user enters 12.5 for the radius, she should get the same number as in the previous item. 3. Create another program by modifying the program from item 2 so that if the user enters a number less than zero, the reported circumference will be zero than negative. 4. Write a program that prompts for and read two numbers (on separate lines of input) and prints out the product of the two numbers multiplied together. 5. Write a program that prompts for and reads a string and a number (on a separate lines of input) and prints out the string the number of times indicated by the number on separate lines. If the user enters E-Mac and 2 the output should be two lines each saying E-Mac.

Vous aimerez peut-être aussi