Specifying a List In Your Program
Problem
You want to include a list in your program. This is how you initialize arrays.
Solution
You can write out a comma-separated list of elements:
@a = ("quick", "brown", "fox");If you have a lot of single-word elements, use the
qw()
operator:
@a = qw(Why are you teasing me?);
If you have a lot of multi-word elements, use a here document and extract lines:
@lines = (<<"END_OF_HERE_DOC" =~ m/^\s*(.+)/gm);
The boy stood on the burning deck,
It was as hot as glass.
END_OF_HERE_DOCDiscussion
The first technique is the most commonly used, often because only small arrays are normally initialized as program literals. Initializing a large array would fill your program with values and make it hard to read, so such arrays are either initialized in a separate library file (see Chapter 12), or the values are simply read from a file:
@bigarray = ();
open(DATA, "< mydatafile") or die "Couldn't read from datafile: $!\n";
while (<DATA>) {
chomp;
push(@bigarray, $_);
}The second technique uses the qw() operator, one
of the quoting operators. Along with
q()
,
qq(), and qx(),
qw()
provides
another way to quote values for your program. q()
behaves like single quotes, so these two lines are equivalent:
$banner = 'The Mines of Moria'; $banner = q(The Mines of Moria);
Similarly, qq() behaves like double quotes:
$name = "Gandalf"; $banner = "Speak, $name, and enter!"; $banner = qq(Speak, $name, and welcome!);
And qx() is almost exactly like backticks; that is, it ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access