Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

How can I start incrementing an index at 0?

( #30840=categorized question: print w/ replies, xml ) Need Help??
Contributed by raj8 on Sep 02, 2000 at 05:25 UTC
Q&A  > arrays


Description:

Hello Perl Monks, I am have been attempting to unpack columns and increment the output, however, the increment operator starts at 1. Here is an example output:
drive 0 dirve 1 drive 2 drive 3 I am using this: open(LIST,"list -l|"); while(<LIST>) { ($drive) = unpack '@0 A3',$_; if(/Drive/) { $count++; } system("list -delete -dr -index ${count}"); }; However, when it gets to 3 it says can't delete 4 because the $i++ started at 1 instead of 0.
Any suggestions would help. thanks-- raj8

Answer: How can I start incrementing an index at 0?
contributed by Adam

First of all, the quick answer: declare $count = -1; somewhere earlier.

Next the long answer. Your code is not good for a variety of reasons, most of which you learn from practice and experience, which if you hang out here you will gain quickly. Try this:

use strict; # always. my $drive; my $count = -1; open( LIST, "list -l|" ) or die $!; while(<LIST>) { ($drive) = unpack '@0 A3',$_; ++$count if m/Drive/; system("list -delete -dr -index ${count}"); }
This code can still made better, but that should get you off to a good start.

Please (register and) log in if you wish to add an answer



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • Outside of code tags, you may need to use entities for some characters:
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.
  • Log In?
    Username:
    Password:

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

    How do I use this? | Other CB clients
    Other Users?
    Others contemplating the Monastery: (18)
    As of 2014-07-10 14:33 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?

      When choosing user names for websites, I prefer to use:








      Results (212 votes), past polls