Re: qw vs. q
- From: rick@xxxxxxxxxxxxxxxxxxxxx (Rick Scott)
- Date: Mon, 27 Feb 2006 10:32:16 -0800
(John Smith <wleung7@xxxxxxxxx> uttered:)
I found the following example on CPAN:
my $key = 'welcome';
my %data = (
'this' => qw(that),
'tom' => qw(and jerry),
'welcome' => q(Hello World),
'zip' => q(welcome),
);
my @data = keys %data;
First of all, bear in mind that that's a contrived example from
perldebtut, the debugging tutorial, and it has errors. Run it with
strictures and warnings (use strict; use warnings;) and you get:
Odd number of elements in hash assignment at ./foo.pl line 9.
....because what that code actually means is
my %data = (
'this', 'that',
'tom', 'and', 'jerry',
'welcome', 'Hello World',
'zip', 'welcome',
);
my question is:
1) what is the difference between qw and q?
qw is the word list quoting operator. Instead of giving you back
one string like '' and "" do, it returns a list of the whitespace-
separated `words' inside.
q{foo} is just a more general way of saying 'foo' -- it works exactly
like singlequotes. Similarly, qq{bar} is just a more general way of
saying "bar" -- qq works just like doublequotes. See the "Quoting and
Quote-like operators" section of perlop:
perldoc perlop
To wit:
qw(that) # gives you one item: 'that'
qw(and jerry) # gives you TWO items: 'and', 'jerry'
q(Hello World) # gives you ONE item: 'Hello world'
q(welcome) # gives you one item: 'welcome'
2) why is qw used in first 2 key-element; and q used in last 2
key-element?
Using qw to assign specifically to hash *values* like your example did
doesn't make sense. Hash values have to be single values, and qw is
generally used when you're looking for a list. Using qw to assign to
a whole hash, on the other hand, is a common idiom:
my %pt_number = qw{
1 um 2 dois 3 tres 4 quatro 5 cinco
6 seis 7 sete 8 oito 9 nove 10 dez
}
Cheers,
Rick
--
key CF8F8A75 / print C5C1 F87D 5056 D2C0 D5CE D58F 970F 04D1 CF8F 8A75
It is very little to me to have the right to vote,
to own property, etcetera, if I may not keep my body,
and its uses, in my absolute right. :Lucy Stone
.
- References:
- qw vs. q
- From: John Smith
- qw vs. q
- Prev by Date: Re: A Problem With GD
- Next by Date: MIME::Parser
- Previous by thread: Re: qw vs. q
- Next by thread: MIME::Parser
- Index(es):