SPUG: re: slice
ced at carios2.ca.boeing.com
ced at carios2.ca.boeing.com
Mon May 8 22:12:07 CDT 2000
Replying to Rob G.'s question. Sorry to lose the thread...
It's Monday :).
> ...but I was surprised:
> $DATA{ $key }[0] = $val; # same as $DATA{ $key }->[0] = $val;
> is proper syntax to assign a value to a anon array ref stored in a hash,
> correct?
Right. Either works.
> So I was expecting array slices to behave in the same manner by replacing a
> single subscript with a range of subscripts. But this didn't seem to work:
> $DATA{ $key }[1,2,3,4] = @prices[0,1,2,3];
> Thinking I understand and really understanding are !=. Is the difference
> between the 2 lines that the slice turns the array operation into a list
> operation?
> And, therefore, the [1,2,3,4] no longer is telling perl that
> $DATA{ $key } is an array reference? So perl thinks that I'm trying to do
> what?
I believe the $ in $DATA{}[] will propagate a scalar context for
both the index [1,2,3,4] and the slice @prices[] on the RHS. In
both cases, the list will reduce to the final element.
So, the above becomes:
$DATA[ $key }[4] = $prices[3];
A hash slice here would have to written:
@{ $DATA{ $key } }[1,2,3,4] = @prices[0,1,2,3];
or, more virtuously, since you'd save keystrokes:
@{ $DATA{ $key } }[1..4] = @prices[0..3];
A bit tricky because $DATA{ $key } is an array reference
and the binding precedence won't allow you to get away with:
@$DATA{ $key }[1,2,3,4]
The tokener thinks $DATA alone contains the array ref. so
you have to give it some help with the {}.
Hope this isn't too far off the mark. Again, Perl Data Structure
Cookbook probably has far better explanations.
Rgds,
--
Charles DeRykus
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
POST TO: spug-list at pm.org PROBLEMS: owner-spug-list at pm.org
Seattle Perl Users Group (SPUG) Home Page: http://www.halcyon.com/spug/
For Subscriptions, Email to majordomo at pm.org: ACTION spug-list EMAIL
Replace ACTION by subscribe or unsubscribe, EMAIL by your Email address
More information about the spug-list
mailing list