John said:
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;
my question is:
1) what is the difference between qw and q?
Here is a quote about "qw" from perldoc perlop:
+++++++++++++++++++++++++++++++++++++++++++++++++++++++
++ qw/STRING/
++ Evaluates to a list of the words extracted out of
++ STRING, using embedded whitespace as the
++ word delimiters. It can be understood as being
++ roughly equivalent to:
++
++ split(' ', q/STRING/);
++
++ the differences being that it generates a real list
++ at compile time, and in scalar context it returns
++ the last element in the list. So this expression:
++
++ qw(foo bar baz)
++
++ is semantically equivalent to the list:
++
++ 'foo', 'bar', 'baz'
+++++++++++++++++++++++++++++++++++++++++++++++++++++++
Here is a quote about "q" from perldoc perlop:
+++++++++++++++++++++++++++++++++++++++++++++++++++++++
++ q/STRING/
++ 'STRING'
++ A single-quoted, literal string. A backslash
++ represents a backslash unless followed by the
++ delimiter or another backslash, in which case the
++ delimiter or backslash is interpolated.
++
++ $foo = q!I said, "You said, 'She said it.'"!;
++ $bar = q('This is it.');
++ $baz = '\n'; # a two-character string
+++++++++++++++++++++++++++++++++++++++++++++++++++++++
2) why is qw used in first 2 key-element; and q used in last 2
key-element?
To understand what's going on, one needs to look also at the Comma
Operator "=>":
Here is a quote about "=>" from perldoc perlop:
+++++++++++++++++++++++++++++++++++++++++++++++++++++++
++ Comma Operator
++ Binary "," is the comma operator. In scalar
++ context it evaluates its left argument, throws
++ that value away, then evaluates its right
++ argument and returns that value. This is just
++ like C's comma operator.
++
++ In list context, it's just the list argument
++ separator, and inserts both its arguments into
++ the list.
++
++ The "=>" operator is a synonym for the comma,
++ but forces any word (consisting entirely of word
++ characters) to its left to be interpreted as a string
++ (as of 5.001). If the argument on the left is not
++ a word, it is first interpreted as an expression,
++ and then the string value of that is used.
++
++ The "=>" operator is helpful in documenting the
++ correspondence between keys and values in
++ hashes, and other paired elements in lists.
+++++++++++++++++++++++++++++++++++++++++++++++++++++++
So, the example basically says:
my %data = ('this', 'that', 'tom', 'and', 'jerry',
'welcome', 'Hello World', 'zip', 'welcome');
That could equally be written as:
my %data = (
'this' => 'that',
'tom' => 'and',
'jerry' => 'welcome',
'Hello World' => 'zip',
'welcome'
);
Note that the number of elements in the list is not even, so you will
get a warning "Odd number of elements in hash assignment" when you run
this example.