4.1. Specifying a List In Your ProgramProblemYou want to include a list in your program. This is how you initialize arrays. SolutionYou can write out a comma-separated list of elements: @a = ("quick", "brown", "fox");
If you have a lot of single-word elements, use the @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_DOC DiscussionThe 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, Packages, Libraries, and Modules ), 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 $banner = 'The Mines of Moria'; $banner = q(The Mines of Moria);
Similarly, $name = "Gandalf"; $banner = "Speak, $name, and enter!"; $banner = qq(Speak, $name, and welcome!);
And $his_host = 'www.perl.com'; $host_info = `nslookup $his_host`; # expand Perl variable $perl_info = qx(ps $$); # that's Perl's $$ $shell_info = qx'ps $$'; # that's the new shell's $$
Whereas @banner = ('Costs', 'only', '$4.95'); @banner = qw(Costs only $4.95); @banner = split(' ', 'Costs only $4.95'); All quoting operators behave like regular expression matches, in that you can select your quote delimiters, including paired brackets. All four kinds of brackets (angle, square, curly, and round ones) nest properly. That means you can easily use parentheses or braces (or the other two) without fear, provided that they match up: @brax = qw! ( ) < > { } [ ] !; @rings = qw(Nenya Narya Vilya); @tags = qw<LI TABLE TR TD A IMG H1 P>; @sample = qw(The vertical bar (|) looks and behaves like a pipe.); If you don't want to change the quoting character, use a backslash to escape the delimiter in the string: @banner = qw|The vertical bar (\|) looks and behaves like a pipe.|;
You may only use @ships = qw(Niña Pinta Santa María); # WRONG @ships = ('Niña', 'Pinta', 'Santa María'); # right See Also
The "List Value Constructors" section of
perldata
(1); the
"List Values and Arrays"
section of
Chapter 2
of
Programming Perl
; the "Quote and Quote-Like Operators" section of
perlop
(1); the Copyright © 2002 O'Reilly & Associates. All rights reserved. |
|