Printing number of elements in an array

D

Derek Basch

I just started with Perl after programming in Python for many years and
I must say it is driving me friggin nuts. For instance why does the
first method of printing the number of elements in an array work but
the second prints nothing?

print $temp = @fields;

$temp = @fields;
print $temp

Thanks,
Derek Basch
 
E

Eric Schwartz

Derek Basch said:
I just started with Perl after programming in Python for many years and
I must say it is driving me friggin nuts. For instance why does the
first method of printing the number of elements in an array work but
the second prints nothing?

Assuming you put

my @fields = qw/one two three/;
print $temp = @fields;

$temp = @fields;
print $temp

This works fine. Both print statements output '3'. Of course, you
didn't put a newline between them, so you'll see '33' on your screen,
but that's a technicality of output.

-=Eric
 
D

Derek Basch

Ahhh. Found it. I had not put a line terminator after:

print $temp

It should have been:

print $temp;

Now I get an integer either way.

Thanks,
Derek
 
J

John Bokma

Marc Dashevsky said:
use warnings;
use strict;

my @fields = (0..8);
my $temp;

print $temp = @fields, "\n";
$temp = @fields;
print $temp, "\n";

how about print scalar( @fields), "\n"; ?
 
B

Brian McCauley

Derek said:
Ahhh. Found it. I had not put a line terminator after:

print $temp

It should have been:

print $temp;

Now I get an integer either way.

There is no need to put a semicolon after a Perl statement. It's not a
terminator, it's a separator. Was this perhaps not the last line in
your code?

Note: you should get into the habit of putting "use strict'" and "use
warnings" at the top of even the simplest script. Doing so would
probably have caused Perl to higlight your error. In this case it
would probably have got upset that you were trying to use the string
"3" in a context where a file handle was exepected and said...

Can't use string ("3") as a symbol ref while "strict refs" in use

Without "use strict" Perl will silently convert the string "3" into a
reference to a filehandle called 3 and you'd get a warning...

print() on unopened filehandle 3

Without "use warnings" either Perl will silently discard output sent to
an unopened file handle.
 

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

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top