On Saturday, May 31, 2003, at 12:51 PM, Richard Heintze wrote:

my $x= {'d' => 'y', 'f' => 'g'},
    $y = ['a', 'b', 'c', 'd'];

I am surprised this works. I would write this as:


my($x, $y) = ( { d => 'y', f => 'g' }, [ qw(a b c d) ] );

The => operator automatically quotes barewords in front of it and the qw() construct is a convenient way to get a list of word chunks.

You do realize these are references though, right? If you just want a simple array and hash, these would be much better:

my %x = ( d => 'y', f => 'g' );
my @y = qw(a b c d);

Finally, I realize these are probably only examples, but you should try and use variable names more meaningful than x and y.

# This works! Good!
foreach my $i (@{$y}){ print "array i = $i\n" }

# (1) Why does not this work? How do I index an array?
# (2) How do I compute the length of y instead of hard
coding 3?
for(my $i = 0; $i <= 3; $i++) {

An array, in scalar context, returns the number of elements it contains, so just replace the 3 with what you used above @{$y}. If you're using a simple array, it's even easier at @y.


print "y[$i] = "[EMAIL PROTECTED]"\n";

This line has two errors. First the second i should have a $ in front of it and at @ should be a $, since we're talking about a scalar now. This would have triggered a warning, if you have those active, and you really should use 'strict' and 'warnings' almost all the time.


}

# $i receives the proper values
foreach my $i (keys %{$x}) {
  # (4) Why does not this work? How do I index into my
hash?
  print "hash i = $i => ".$x{$i}."\n";

Just like you did the array in the other print call above, ${$y}{$i}. With a simple hash, it would be $x{$i}, which is a little prettier.


}


my %z= ('d' => 'y', 'f' => 'g'); foreach my $i (keys %z) {

# (5) Why does $z work instead of %z here?
   print "z{$i} = $z{$i}\n";

Because we're talking about a single scalar value now, not the whole hash.


}

Hope this helps.


James


-- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]



Reply via email to