# Scalar Data and Operators in Perl

This chapter is from the book

## Another Example: Stocks

To cement what you've learned today, let's work through another simple example that uses assignment, while loops, if conditionals, pattern matching, input, and both print and printf statements.

This example is a stock performance tracker. All you do is enter the purchase price of your stock and its current price, and it tells you if your investment has lost money, made money, or broken even, and by what percentage:

```% stock.pl
Enter the purchase price: 45
Enter the current price: 48
Your return on investment is 6.7%
% stock.pl
Enter the purchase price: 45
Enter the current price: 40
Your return on investment is -11.1%
% stock.pl
Enter the purchase price: 45
Enter the current price: 45
Your return on investment is 0.0%```

Stock prices must be entered as decimals (not fractions such as 14 5/8), and must be digits. We'll check for both of these things in the script.

Listing 3.2 shows the code for our simple stock tracker. Before reading the following description see if you can go through the code and understand what's going on here.

#### Listing 3.2 The stock.pl Script

```1: #!/usr/local/bin/perl -w
2:
3: \$start = 0;
4: \$end = 0;
5: \$return = 0;
6:
7: while () {
8:   print "Enter the purchase price: ";
9:   chomp (\$start = <STDIN>);
10:
11:   print "Enter the current price: ";
12:   chomp (\$end = <STDIN>);
13:
14:   if (\$start eq '' or \$end eq '' ) {
15:     print "Either the purchase or current price is missing.\n";
16:     next;
17:   }
18:
19:   if (\$start =~ /\D/ or \$end =~ /\D/ ) {
20:     if (\$start =~ /\// or \$end =~ /\//) {
21:       print "Please enter prices as decimal numbers.\n";
22:       next;
23:     } else {
25:       next;
26:     }
27:   }
28:
29:   last;
30: }
31:
32: \$return = (\$end - \$start) / \$start * 100;
33:
34: if (\$start > \$end) {
35:   print "Your investment has lost money.\n";
36: } elsif (\$start < \$end ) {
38: } else {
39:   print "Your investment has broken even.\n";
40: }
41:
42: print "Your return on investment is ";
43: printf("%.1f%%\n", \$return);```

This example has three main sections: an initialization section, a section for getting and verifying input, and a section for calculating and printing the result. I'm going to skip the initialization because you've already seen a bunch of them and you know what they look like by now.

### Getting and Verifying the Input

This while loop, in lines 7 to 30, is for getting the initial input from the user and is the most complex part of this script:

```7: while () {
8:   print "Enter the purchase price: ";
9:   chomp (\$start = <STDIN>);
10:
11:   print "Enter the current price: ";
12:   chomp (\$end = <STDIN>);
13:
14:   if (\$start eq '' or \$end eq '' ) {
15:     print "Either the purchase or current price is missing.\n";
16:     next;
17:   }
18:
19:   if (\$start =~ /\D/ or \$end =~ /\D/ ) {
20:     if (\$start =~ /\// or \$end =~ /\//) {
21:       print "Please enter prices as decimal numbers.\n";
22:       next;
23:     } else {
25:       next;
26:     }
27:   }
28:
29:   last;
30: }```

Initially this will look very similar to the while loop in the stats.pl script: same infinite loop, same if test with pattern matching. But there are some significant differences here.

The most important difference to note is that stats.pl repeats over and over again until the user is done inputting data, whereas this script only needs two pieces of correct data and then it's done. In fact, blank input here is an error, and should be tested for. The other two errors we are checking for are nondigit input, and input made in fractional format (14 5/8, for example). We could lump the latter two together because the slash character / is a nondigit character, but printing a more specific error in that specific case makes for a more user-friendly script.

Our infinite loop, then, will continue looping until we get two acceptable pieces of numeric data. Then we can break out of the loop and move on.

Lines 8 through 12 enable you to look at things line by line. They prompt for the data, and store that data in the scalar variables \$start and \$end. Note that we prompt for both values before testing for validity, rather than doing one at a time. (One at a time would make more sense, usability-wise, but given what you know so far about Perl we would have to duplicate a lot of code, so this way is shorter).

In lines 14 through 17 we test both \$start and \$end to see if they are empty, that is, if the user pressed Return without entering any data. If they did, we call next, which skips to the end of the loop and restarts again from the beginning, prompting again for the data.

In the if statement starting in line 19 things start getting weird. Line 19 is the same test for nondigitness you saw in the stats program; this pattern checks for any input that contains data that isn't a number. This test will trap both data that is completely nonsensical for the script, along with data that might make conceptual sense but that we can't handle—the fractional numbers that I mentioned earlier (14 5/8, 101 15/16, and so on, as stock prices are sometimes listed).

If the test in line 19 is true, the code in line 20 and onward begins executing. That code in-cludes the test in line 20. This test is a character pattern for a single slash—we have to backslash it here because its inside the pattern matching operator. This test, then, is here to trap those fractional numbers. If this test returns true, lines 21 and 22 are executed; we print an error (a hint, actually, and next is called to skip to the end of the loop and restart again).

If the test in line 20 is not true—that is, if we have data that contains something other that a digit, but that doesn't contain a slash—then the code in lines 23 through 26 gets executed. The else clause is part of the if conditional. In an if conditional, if the test is true, the first block of code inside the curly braces is executed. If the test is false, Perl looks for the else clause, and if there is one, then that code gets executed instead. Depending on the state of the test, you'll get either one block or another—never both.

In this case, if we have nonnumeric data that doesn't contain a slash, say, "rasberry", that data will return true for the test in line 19, so the block going from lines 19 to 27 will get executed. The test in line 20, however, will be false—no slash—so Perl will skip lines 20 through 22 and instead execute the else block in lines 23 through 26; print an error, and call next to again run through the same prompting-and-testing loop.

The else part of the if conditional is optional—if there isn't one and the test is false, Perl just goes on executing. So if the user does indeed enter the right data, then the tests in lines 14 and 19 will be false. None of the code in lines 14 through 17 or lines 19 through 27 gets executed if the data is correct. Perl just goes straight down to line 29; last, which breaks us out of the while loop to stop asking for data.

### Calculating and Printing the Result

With correct data in hand, we can go ahead and perform some arithmetic without worrying that what we've actually been given is a string or some weird combination of numbers and strings. All that is behind us now. Line 32 computes the percentage return on investment and stores it in the variable \$return.

`32: \$return = (\$end - \$start) / \$start * 100;`

Note that we need the parentheses around the subtraction here to change the operator precedence. Without the parentheses, the division and multiplication would have been performed first, and then the subtraction, which would not have been correct.

Lines 34 through 40 print our little report on how your investment is doing, and here you can see more ifs and elses. The one in the middle—elsif—is just a shorthand notation for nesting if conditionals inside else statements. You'll learn more about it on Day 6.

Nested ifs, as this structure is called, is a way of cascading different tests and results. You'll see a lot of these sorts of structures. The tests start at the top, and if a test is true, that result is printed, and the nested if is over. Perl skips to the bottom and doesn't do any more tests. If the test is false, another test is tried until one matches or the final else at the end is the default result.

In this case, there are only three possible results: \$start can be less than \$end, start can be greater than \$end, or \$start and \$end can be equal. In the first two tests we check for the first two cases. The last case doesn't need a test because it's the only possible remaining outcome, so it gets caught in the final else in lines 38 through 40.

The final lines, 42 and 43, print out the percentage return on investment we calculated in line 32. Here we use a printf instead of a print, so that we can format the floating-point number to have a single digit of precision.

`43: printf("%.1f%%\n", \$return);`

In this line, %.1f is the formatting code—.1 for the single digit after the decimal point, f for a floating-point number. The two percents after the formatting code (%%) are used to print out an actual percent character in the output. \n, as you know, is a newline, therefore, the result looks something like this:

`Your return on investment is 110.9%`

### InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

## Overview

Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

## Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

### Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

### Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

### Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

### Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

### Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

### Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

## Other Collection and Use of Information

### Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

### Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

### Do Not Track

This site currently does not respond to Do Not Track signals.

## Security

Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

## Children

This site is not directed to children under the age of 13.

## Marketing

Pearson may send or direct marketing communications to users, provided that

• Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
• Such marketing is consistent with applicable law and Pearson's legal obligations.
• Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
• Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

## Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

## Choice/Opt-out

Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

## Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

## Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

## Sharing and Disclosure

Pearson may disclose personal information, as follows:

• As required by law.
• With the consent of the individual (or their parent, if the individual is a minor)
• In response to a subpoena, court order or legal process, to the extent permitted or required by law
• To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
• In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
• To investigate or address actual or suspected fraud or other illegal activities
• To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
• To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
• To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.