I'm missing something!!!

J

Jeff

The script:

#!/usr/bin/perl -w
use strict;

my %hash = (
'grid' => 1,
'grab' => 2,
'grub' => 3,
);

foreach my $key (sort keys %hash){
print $key " => ". $hash{$key} . "\n";
}


the result:
Can't use string ("grab") as a symbol ref while "strict refs" in use at
papa line 11.

without strict, I get this result:
print() on unopened filehandle grab at papa line 11.
print() on unopened filehandle grid at papa line 11.
print() on unopened filehandle grub at papa line 11.

Any thoughts?

Jeff
 
B

Brian Wakem

Jeff said:
The script:

#!/usr/bin/perl -w
use strict;

my %hash = (
'grid' => 1,
'grab' => 2,
'grub' => 3,
);

foreach my $key (sort keys %hash){
print $key " => ". $hash{$key} . "\n";

^^ Missing .
 
X

Xicheng

Jeff said:
The script:

#!/usr/bin/perl -w
use strict;

my %hash = (
'grid' => 1,
'grab' => 2,
'grub' => 3,
);

foreach my $key (sort keys %hash){
print $key " => ". $hash{$key} . "\n";

perl treats this barebone variable "$key" as filehandle reference...
add a comma after $key...

Xicheng
 
J

Jeff

Brian and Xicheng:

Thanks, you guys are great. I've been staring at code for too many
continuous hours...

Jeff
 
J

Jeff Stampes

Jeff said:
print $key " => ". $hash{$key} . "\n";

Other people have identified your problem for you.

If you don't have the background in other programming languages (like me!), it's hard to
remember printf() sometimes...but your print above would become:

printf "%s => %s\n", $key, $hash{ $key };

You could even use each() in your look instead, and have:

while ( my ($key, $value) = each %hash ) {
printf "%s => %s\n", $key, $value;
}

Which I find more readable (despite the fact I never think to write it that way!)

Just showing MOTOWTDI

~Jeff
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,571
Members
45,045
Latest member
DRCM

Latest Threads

Top