Home > Articles > Web Development > Perl

This chapter is from the book

Getting Elements Out of an Array

So far in this hour, you've been slinging around whole arrays and lists and putting information into arrays. How can you get that information back out?

One way to get the contents of the entire array is to put the array variable in double quotation marks:

print "@array";

An array in double quotes is interpolated, and its elements are returned separated by spaces. This example prints the elements of @array with a space separating each element.

Many times, though, you need to get to individual elements of arrays. You may need to search for an element, change the value of an element, or to add or remove individual elements in an array.

Individual elements in an array are accessed by a numeric index. The index for array elements starts at the number 0 and increases by 1 for each additional element. Each element of the array has an index value, as shown in the following figure.

Figure 4.3

The number of elements in an array is limited only by your system's memory. To access an element, you use the syntax

$array[index]

where array is the array name and index is the index of the element you want (also called a subscript). The array doesn't have to exist before you refer to individual elements; if it does not already exist, it just automagically springs into existence. Some examples of accessing array elements follow:

@trees=qw(oak cedar maple apple);
print $trees[0];		# Prints "oak"
print $trees[3];		# Prints "apple".
$trees[4]='pine';

Notice that to talk about an individual element of @trees, the code uses a $. "I thought the $ marker was usually reserved for scalars; what's going on?" you might ask. The answer is that the $ in $trees[3] does refer to a scalar: one scalar value within @trees. (Scalars are also indicated by a dollar sign because they're singular as well. You should notice a pattern here.)

At the beginning of this hour, you discovered that scalars and arrays can have the same variable names and remain unrelated. Perl can tell the difference between $trees, a scalar variable that has nothing to do with the @trees array, and $trees[0], the first element in the @trees array, because of the square brackets in $trees[0]. Perl knows that you're taking about the first element of @trees and not talking about $trees at all.

You can also talk about a subgroup within an array, called a slice. To take a slice of an array, you use both the @ type identifier—to indicate that you're talking about a group of things—and square brackets—to indicate you're talking about individual elements of an array, as shown here:

@trees=qw(oak cedar maple apple cherry pine peach fir);
@trees[3,4,6];		 # Just the fruit trees
@conifers=@trees[5,7]; # Just the conifers

Finding the End of an Array

Sometimes you need to find the end of the array—for example, to see how many trees are in the @trees array or to cut some trees out of the @trees array. Perl provides a couple of mechanisms for finding the end. The first is a special variable in the form $#arrayname. It returns the number of the last valid index of the array. Check out this example:

@trees=qw(oak cedar maple apple cherry pine peach fir);
print $#trees;

This example contains eight elements, but you must remember that arrays are numbered starting at 0. So the preceding example prints the number 7. Modifying the value of $#trees changes the length of the array. Making it smaller truncates the array at whatever index you specify, and making it larger gives the array more elements. The newly added elements all have their values set to undef.

The other method of finding the size of an array is to use the array variable in a place where a scalar is expected:

$size=@array;

This puts the number of elements in @array into $size. This takes advantage of a Perl concept called context, explained in the next section.

NOTE

You can also specify negative indexes for arrays. Negative index numbers start counting from the end of the array and work backward. For example, $array[-1] is the last element of @array, $array[-2] is the next to the last element, and so on.

Learning More about Context

What is context? Context means the things that surround an item of interest to help define what that item means. For example, seeing a man in surgical scrubs can have different meanings depending on where he is: In a hospital, the fact that the man is wearing scrubs might mean that he's a doctor; at a Halloween party, he could be just another party guest in costume.

Human language uses context to help determine the meaning of words. For example, the word level can have several different meanings depending on how it's used and what context it's in:

  • The carpenter used a level to hang the door straight.

  • The moderator spoke in a level tone.

  • The water in the pool was at waist level.

It's the same word each time, but the meaning has changed. It becomes a noun, an adjective, and a different kind of noun depending on how it's used in a sentence.

Perl is also sensitive to context. Functions and operators in Perl can behave differently depending on what context they're used in. The two most important contexts in Perl are list context and scalar context.

As you've seen, you can use one operator—the equals sign—to perform assignment with both arrays and scalars. The type of expression (list or scalar) on the left side of the assignment operator determines what context the things on the right side are evaluated in, as shown in the following lines of code:

$a=$b;	    # Scalar on the left: this is scalar context.
@foo=@bar;  # Array on the left: this is list context.
($a)=@foo;  # List on the left: this is also list context.
$b=@bar;	 # Scalar on the left: this is scalar context.

The last line is interesting, because it puts an array into scalar context. As was stated in the previous section, evaluating an array in a scalar context returns the number of elements in the array.

More about the Size and End of an Array

Observe $a and $b in the following few lines of code; they do almost the same thing:

@foo=qw( water cola juice lemonade );
$a=@foo;
$b=$#foo;
print "$a\n";
print "$b\n";

At the end of this code, $a contains the number 4, and $b contains the number 3. Why the difference? $a is @foo evaluated in a scalar context, and it contains the number of elements. $b, on the other hand, is set to the index of the last element, and indexes start counting at 0.

Because arrays in a scalar context return the number of elements in the array, testing whether an array contains elements becomes this simple:

@mydata=qw( oats peas beans barley );
if (@mydata) {
	print "The array has elements!\n";
}

Here, the array @mydata is evaluated as a scalar, and it returns the number of elements—in this case, 4. The number 4 evaluates to true in an if statement, and the body of the if block is run.

NOTE

Actually, @mydata here is used in a special kind of scalar context called a Boolean context, but it behaves the same way. Boolean context occurs when Perl expects a true or false value, such as in an if statement's test expression. One other context, called void context, will be explained in Hour 9, "More Functions and Operators."

Context with Operators and Functions

Many of Perl's operators and functions force their arguments to be either scalar context or list context. Sometimes the operators or functions behave differently depending on what context they're in. Some functions you've already encountered have these properties; however, this fact hasn't been important until now, because they have only had scalars to work on.

The print function expects a list as an argument. It doesn't particularly matter what context the list is evaluated in, though. So printing an array with print like this causes the array to be evaluated in a list context, yielding the elements of @foo:

print @foo;

You can use a special pseudofunction called scalar to force something into a scalar context:

print scalar(@foo);

This example prints the number of elements in @foo. The scalar function forces @foo to be evaluated in a scalar context, so @foo returns the number of elements in @foo. Then the print function simply prints the number returned.

The chomp function you learned about in Hour 2, "Perl's Building Blocks: Numbers and Strings," takes either an array or a scalar as an argument. If chomp is presented with a scalar, it removes the record separator from the end of the scalar. If it is presented with an array, it removes the record separator from the end of each scalar in the array.

Also in Hour 2 you learned how to read a line of input from the keyboard by using <STDIN>. The angle brackets (<>) are really an operator in Perl, and they behave differently depending on context. In a scalar context, this operator reads one line of input from the terminal. In a list context, however, it reads all the input from the terminal—until the End of File is read—and places the data in the list. Examine the following:

$a=<STDIN>;  # Scalar context, reads one line into $a.
@whole=<STDIN>; # List context, reads all input into the array @whole.
($a)=<STDIN>; # List context, reads all input into the assignable list.

In the third example, what does $a receive? Remember from earlier in this hour that if the left side in a list assignment doesn't have enough variables to hold all the right-side elements, the extra right-side elements are dropped. So here all input from the terminal is read, but $a receives only the first line.

NOTE

What's an End of File? When Perl reads all input from a terminal, you need to signal when you're done feeding Perl data. You usually do so typing an end-of-file (EOF) character. That character differs depending on your operating system. Under Unix, that character is usually a Ctrl+D at the beginning of a line. On MS-DOS or Windows systems, that character is Ctrl+Z two times anywhere in the input.

Also in Hour 2 you learned about the repetition operator x. The repetition operator has a special behavior in list context. If the left operand is in parenthesis, and the operator itself is used in a list context, it returns a list of the left operand repeated. The following example builds an array of 100 stars:

@stars= ("*") x 100;

The left operand of x"*"—is in parentheses, and assigning it to an array puts it in a list context. This syntax is useful for initializing an array's elements to a particular value.

Another operator that you've been using—and probably didn't know it was an operator—is the comma (,). Until now, you've been using the comma to separate elements of literal lists, like this:

@pets=('cat', 'dog', 'fish', 'canary', 'iguana');

The preceding snippet has the list being evaluated in a list context, as normal. In a scalar context, on the other hand, the comma is an operator that evaluates each element from left to right and returns the value of the rightmost element:

$last_pet=('cat', 'dog', 'fish', 'canary', 'iguana');  # Not what you think!

In this snippet, the pets named on the right side of the assignment operator aren't really a list, despite the parentheses around them. The right side of the expression is evaluated in a scalar context because of the scalar $last_pet on the left of the equals sign, so the group of string literals is evaluated as a scalar. The result is that $last_pet is set equal to 'iguana'.

Another example of a function that acts in two completely different ways depending on which context it's in is the localtime function. In a scalar context, the localtime function returns a nicely formatted string with the current time. For example, print scalar(localtime); would print something like: Thu Sep 16 23:00:06 1999. In a list context, localtime returns an list of elements that describe the current time:

($sec, $min, $hour, $mday, $mon, $year_off, $wday, $yday, $isdst)=localtime;

What these values represent is shown in Table 4.1.

Table 4.1 Return Values from localtime, in List Context

Field

Value

$sec

Seconds, 0–59

$min

Minutes, 0–59

$hour

Hour, 0–23

$mday

Day of the month, 1–28, 29, 30, or 31

$mon

Month of the year, 0–11 (be careful here!)

$year_off

-Number of years since 1900 (add 1900 to this number for the correct 4-digit year)

$wday

Day of the week, 0–6

$yday

Day of the year, 0–364 or 365

$isdst

True if Daylight Savings Time is in effect


NOTE

Do not attempt to get a four-digit year by concatenating '19' in front of the year returned by localtime. The year returned is an offset from 1900—in 1999, year is '99'; in 2001 it is '101'. Adding 1900 to this value will work correctly well beyond year 2000. Perl has no Y2K bugs, but simply concatenating '19' (or '20') with the year will cause a Y2K problem in your programs.

How do you know what context a function or operator forces on its arguments and how it's going to function depending on whether it's in a scalar context or a list context? Quite simply, you don't, and there's really no good way to guess. The online documentation lists each function and operator and explains these factors for each one if you're unsure. For the remainder of this book, if a function or operand forces a context on its arguments, or behaves differently depending on what context it's evaluated in, I will indicate all these points when the function is first presented. It doesn't happen often, but when it does, I'll be sure to tell you.

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.

Newsletters

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.

Cookies and Related Technologies

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.

Links


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.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020