Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!evax!utacfd!letni!mic!convex!convex.COM From: tchrist@convex.COM (Tom Christiansen) Newsgroups: comp.lang.perl Subject: Re: $# question Message-ID: <108795@convex.convex.com> Date: 26 Nov 90 00:55:04 GMT References: <109132@convex.convex.com> Sender: usenet@convex.com Reply-To: tchrist@convex.COM (Tom Christiansen) Organization: CONVEX Software Development, Richardson, TX Lines: 50 In article roy%cybrspc@cs.umn.edu (Roy M. Silvernail) writes: |OK, now consider the following fragment: | |for($x=0;$x<$#foo;$x++) { | @aa = split(/\\/,@foo[$x]); | @bb = split(/\\/,@foo[$x+1]); # forward array reference | $foo[$x] = '' if $bb[$#bb - 1] ne $aa[$#aa - 1]; |} | |Is there a spiffy Perl Way to handle the forward reference in each |iteration without the explicit variable-controlled loop? (or have I |happened upon the occasional exception that demands the for() |construct?) Without trying to come up with something illegibly clever, direct indexing seems the easiest route if you're going to be checking more than the current element. I really do wish you wouldn't do things like this, though: | @aa = split(/\\/,@foo[$x]); This kind of thing makes me nervous. You see, split wants a scalar expression there in the second element. You just passed it a list of one element. While in this case, the difference is minimal, one of these days, it's going to come back to haunt you. Take my word on this one. For example, @a = ('red', 'green', 'blue'); @b[0] = @a; Now the zeroth element of @b is 'red', because you've got arrays on both sides of the assignment, so you got an array copy. Just because @b[0] is only one element long doesn't undo its listishness. Now, if you subscripted it the other way: $b[0] = @a; Then the zeroth element of @b is '3', that is, the length of @a, because you had a scalar context on the RHS of the assignment. Catch that? Moral of the story: when you want to talk about a single element, use $. When you might want more than one, use @. Try not to confuse a list that's one element long with a simple scalar value. If you don't follow this rule, it will someday come back to bite you where you're not looking, and you won't be happy. I promise. --tom