<?xml version="1.0" encoding="windows-1252"?>
<node id="40239" title="Possible pitfall with Slices" created="2000-11-06 19:56:42" updated="2005-07-21 01:21:58">
<type id="115">
perlquestion</type>
<author id="16217">
fundflow</author>
<data>
<field name="doctext">
Dear Monks,
&lt;p&gt;
There is a subtle and quiet way to shoot yourself in the leg
when using array slices. It just happened to me and this
note is posted with the hope to save others this 'pleasure'.

&lt;p&gt;
&lt;bf&gt;Background&lt;/bf&gt;
&lt;p&gt;
Array/hash slices are very convinent for vectorizing operations
on arrays and hashes. For Matlab users (like me) this is very
natural. For example:&lt;code&gt;
	@a[1,2,3] = @b[100,200,300];
&lt;/code&gt;
will copy three of b's elements to a.
&lt;br&gt;
Similarly, for hashes:&lt;code&gt;
	@a{a,b,c}=@b[100,200,300];
&lt;/code&gt;
will put the same elements in the hash a.

&lt;p&gt;
&lt;bf&gt;The Pitfall&lt;bf&gt;
&lt;p&gt;
It order to fill a hash, one can write the following:
&lt;code&gt;
	@a{a,b,c}=1;
&lt;/code&gt;
and after that line, the three elements 'a','b','c' will be
in %a, BUT they will not contain the value 1!&lt;br&gt;
Thus, the following will not give the expected result:
&lt;code&gt;
	for (a,b,c,d) { print "$_\n" if $a{$_} }
OUTPUT:
	a
&lt;/code&gt;
The output contains only 'a' since in the assignment above, 
&lt;code&gt;$a{a}&lt;/code&gt; was assigned the value 1 whereas the 
rest were created, but are undefined. This is because perl 
treats the slice as a list and expects the right-hand side 
to be a list as well, and we only have one element there...
&lt;p&gt;
The right way to do it is:
&lt;code&gt;
	@a{a,b,c}=(1,1,1);
or
	@a{a,b,c}=(1)x3;
&lt;/code&gt;

&lt;p&gt;
The problem here is that this gives a default silent behaviour.
&lt;br&gt;&lt;br&gt;
The matlab approach to this, which is very consistent and
natural is that assignments like this have to have the same
number of elements on both sides. A special case where the
r.h.s. is a scalar, is treated as an array of the appropriate 
size with this repeated element.
&lt;br&gt;&lt;br&gt;&lt;br&gt;
It would be nice if when the r.h.s. in the assignment 
is one element, it will be treated as a list with that
element repeated the correct number of times (i.e. Matlab style).
If this is too hard to implement, it could be useful to 
give a warning/error about that.
&lt;br&gt;
&lt;p&gt;
Notes:&lt;br&gt;
1. if perl is run with -w, then accessing the elements will
warn that the elements are undefined, but this will appear 
in a different location than the assignment&lt;br&gt;
2. Is this the right place in PM for such node?</field>
</data>
</node>
