Printing number of elements in an array

Discussion in 'Perl Misc' started by Derek Basch, Apr 17, 2006.

  1. Derek Basch

    Derek Basch Guest

    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
     
    Derek Basch, Apr 17, 2006
    #1
    1. Advertisements

  2. Assuming you put

    my @fields = qw/one two three/;
    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
     
    Eric Schwartz, Apr 17, 2006
    #2
    1. Advertisements

  3. Derek Basch

    Derek Basch Guest

    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
     
    Derek Basch, Apr 17, 2006
    #3
  4. Derek Basch

    John Bokma Guest

    how about print scalar( @fields), "\n"; ?
     
    John Bokma, Apr 17, 2006
    #4
  5. Derek Basch

    Derek Basch Guest

    Thanks for the replies everyone!

    Derek Basch
     
    Derek Basch, Apr 17, 2006
    #5
  6. 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.
     
    Brian McCauley, Apr 18, 2006
    #6
    1. Advertisements

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 (here). After that, you can post your question and our members will help you out.