--- Bryan R Harris <[EMAIL PROTECTED]> wrote: > > Thanks Ovid, Timothy... > > You mention checking out perlref in the perldocs-- I'm familiar with > "perldoc -f keyword", but how would I find information on these things if I > didn't know the keyword "perlref"? (Apparently I'm the only legitimate > "beginner" here! =) > > Oh, and one more question. =) > > $lines[0] = [ "dog", "cat" ]; > print "$lines[0][0,1]\n"; > > This prints "cat". Shouldn't it print "dogcat"?
Timothy answered your question by describing and array slice, but I thought you might want to also know why the above works the way that it does. The following uses an array slice to print what you want: print @{$lines[0]}[0,1]; However, if you just have this: print $lines[0][0,1]; Perl winds up seeing a list inside of the second set of square brackets and when it sees a list, it evaluates every item in turn, from left to right, and the entire expression is the result of the last evaluation. So in this case, the zero evaluates to zero, the one evaluates to one and this reduces to: print $lines[0][1]; However, this behavior should not be relied upon as it's difficult to keep straight: $lines[0] = [ "dog", "cat" ]; Why doesn't that just assign "cat" to the first element of @lines? I'm not sure, but I'm guessing it is because the square brackets are performing a subtle double-duty. In the first example: print $lines[0][0,1]; the square brackets are being used to indicate an array element. In the second example: $lines[0] = [ "dog", "cat" ]; The square brackets are being used to create a reference to an anonymous array and constructs the anonymous array from a list. Keeping things straight can be a major headache. Further, you can get strange warnings: print $lines[0][0,2,1]; That works, but if you have warnings enabled, the 2 produces a "Useless use of a constant in void context ..." warning. Changing the two to a one or zero will eliminate the warning (this might be a bug in Perl, or it might be a hack to allow a "1" to be used at the end of a module without producing a spurious warning -- since all modules need to return a true value). Note that the following, even though it contains a 2, does not produce a warning: #!/usr/bin/perl -w $lines[0] = [ qw/ dog cat bird / ]; print $lines[0][0,0,2]; That's because the 2, being the last item evaluated, is being used as the array index and thus is not being used in void context. Got all that? :) Cheers, Curtis "Ovid" Poe ===== "Ovid" on http://www.perlmonks.org/ Someone asked me how to count to 10 in Perl: push@A,$_ for reverse q.e...q.n.;for(@A){$_=unpack(q|c|,$_);@a=split//; shift@a;shift@a if $a[$[]eq$[;$_=join q||,@a};print $_,$/for reverse @A __________________________________________________ Do You Yahoo!? Yahoo! - Official partner of 2002 FIFA World Cup http://fifaworldcup.yahoo.com -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]