Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical

comment on

( #3333=superdoc: print w/replies, xml ) Need Help??
Be careful... you can change the starting index value to something other than zero. I would not recommend doing so, but if you did, you'd get the wrong value by using scalar.

Let me show you what I mean:

# change the starting index -- usually not a good idea. $[ = 2; # create a sample array @data = qw(one two three four); # try to find the last index value $bad = @data - 1; $still_bad = scalar @data - 1; $good = $#data; # what did we find? print "bad: $bad\n"; # gives 3 print "still bad: $still_bad\n"; # gives 3 print "good: $good\n" # gives 5

So I would recommend two things:

  1. Don't change the starting index value without a very good reason.
  2. Use the $#array_name syntax if you really need the last index value. (Usually, you want the last element, and can just use the negative subscript technique mentioned above.)

Trying to debug someone else's code when they've changed $[ can be particularly annoying.

In reply to Re: How do I find the index of the last element in an array? by ChrisS
in thread How do I find the index of the last element in an array? by vroom

Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":

  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?

What's my password?
Create A New User
Domain Nodelet?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (3)
As of 2023-01-28 10:47 GMT
Find Nodes?
    Voting Booth?

    No recent polls found