in reply to Questions about context
You are correct about what the @{ [ ] } syntax does in your first question. The reason it's written like that is twofold: first, you're trying to call a function within a string interpolation, which simple interpolation of scalar variables and the like doesn't allow. However, you can interpolate an array constructed on the fly just like you have. Second, the code (localtime)[5] means: evaluate the function localtime in list context, and then take the sixth element of the list that it returns. This also explains what is going on in your second example. This is known as a list slice and is explained in more detail in the "Slices" section of perldata.
Update: Thought I'd add some examples. As you've mentioned,
works by taking a list slice, thus forcing localtime to be called in list context. The behavior of a list slice in scalar context, however, is to return the last element of the list, somy $x = (localtime)[0];
would have the same result as the above. Another way to do it ismy $x = (localtime)[2,3,4,0];
This is different. There's no slice here. Instead, the parentheses around the left-hand side of the assignment force the right side to be evaluated in list context, and then the first element returned is assigned to the first scalar lvalue on the left side. BUT, parentheses do not always mean list context. In particular,my ($x) = localtime;
will not do the same thing. Instead it will call localtime in scalar context and assign the result to $x.my $x = (localtime)
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Questions about context
by Anonymous Monk on Jan 30, 2005 at 01:48 UTC | |
by davido (Cardinal) on Jan 30, 2005 at 05:04 UTC | |
by qq (Hermit) on Jan 30, 2005 at 19:53 UTC | |
by borisz (Canon) on Jan 30, 2005 at 02:06 UTC | |
by ysth (Canon) on Jan 30, 2005 at 10:18 UTC | |
by nobull (Friar) on Jan 30, 2005 at 12:21 UTC | |
by ysth (Canon) on Feb 02, 2005 at 06:41 UTC |