Perl string array - How to create and use an array of strings

With Perl we work with strings and arrays (or lists) of strings all the time. I thought I'd take a few moments here to show the most common ways to create a Perl string array, and also to loop through (or iterate through) the list of strings I create.

How to create a Perl string array

When you first start to work with Perl, you might create a string array like the following example:

@pizzas = ("cheese", "pepperoni", "veggie" );

There's nothing wrong with this, but a more "Perl" way of creating this same string array is this:

@pizzas = qw(cheese pepperoni veggie );

Creating a list of words like this is so common, the good folks at Perl created created this qw syntax for just this purpose. It's pretty easy to remember qw, as it stands for "quoted words".

Perl string array loop - looping through an array

There are a number of ways of looping through a Perl string array, but the following source code snippet shows my favorite method, using the Perl foreach loop:

@pizzas = qw(cheese pepperoni veggie );
foreach $pizza (@pizzas) {
  print "$pizza\n";
}

This simple foreach loop produces the following output:

cheese
pepperoni
veggie

As mentioned, there are other ways of looping through Perl arrays, but I prefer the foreach syntax because I can remember it easily, and it also lets me define the $pizza parameter as the keyword inside the loop. In fact, I like the foreach loop so much, I wrote about it being a Perl best practice.

Perl string array - another way to create a list of pizzas

There's at least one other way to create a Perl string array, and I think it's important to show that syntax here, because you are likely to use this syntax when working with dynamic programs, such as when you work with a database.

Here's a sample of how you might create a Perl array dynamically:

$pizzas[0] = 'cheese';
$pizzas[1] = 'pepperoni';
$pizzas[2] = 'veggie';

This array is the same as the previous one, I just created it in a different way.

Note that I used single quotes here. You can use single quotes around strings like this as long as you're not trying to use a variable inside of the quotes. I'll discuss this more in another tutorial.

Just to show that this works, here's the previous foreach loop combined with this different Perl array syntax:

$pizzas[0] = 'cheese';
$pizzas[1] = 'pepperoni';
$pizzas[2] = 'veggie';

foreach $pizza (@pizzas) {
  print "$pizza\n";
}

And here's the output from this simple Perl array/foreach script:

cheese
pepperoni
veggie