Uri,

Using both the array element value & index in a loop is a very
fundamental coding usage (just like using the hash key & value), which I
didn't think needed further elaboration (it's not exactly an esoteric
usage model!). Nevertheless, here is an  example I'm currently working
on (which prompted the question):

I'm parsing a Verilog assign statement & the RHS is a multi-bit
concatenated bus. The key on the LHS includes the "[$i]", so I can use
that to correlate the same signal to another place in the code:

   my $i= 0;
   foreach (@sigs)
   { $mybus{"bus1[$i]"}= $_; $i++; }


I think it'd be fairly easy for Perl to auto initialize & increment a
loop index in all loops & provide that to the user in a special
variable. "$." is an excellent example. I think it'd be a great addition
to Perl's excellent (& long) list of special vars, making for yet more
elegant & concise code.


The "push(@newarray[$_], ..." in my original example was a bad typo -- I
did not intend the '[$_]' ... Thanks for flagging that.

Thanks,

-Nilanjan


-----Original Message-----
From: Uri Guttman [mailto:[EMAIL PROTECTED] 
Sent: Monday, September 18, 2006 12:09 PM
To: Palit, Nilanjan
Cc: boston-pm@mail.pm.org
Subject: Re: [Boston.pm] Loop index in foreach?

>>>>> "PN" == Palit, Nilanjan <[EMAIL PROTECTED]> writes:

  PN> That works too (& I have used it as well), but I guess what I'm
  PN> really asking (hoping?) for is a Perl special variable, kinda like
  PN> "$.", which Perl auto-magically initializes & increments ...

in my experience classic loop indexes are rarely needed in perl. my take
is that coders who want an index value haven't done a proper design. if
you explain the larger problem i bet we could show you ways to bypass
your perceived need for a loop index.

also in your example you are pushing to @newarray[$i] which is not good
perl as it is an array slice with a single index. this will trigger a
warning if you enable warnings. if all you wanted to do was push some
values onto an new array, then map is your answer as someone else
showed. but anyhow we would like to see more info about the problem so
we can help solve it at the proper level.

uri

-- 
Uri Guttman  ------  [EMAIL PROTECTED]  --------
http://www.stemsystems.com
--Perl Consulting, Stem Development, Systems Architecture, Design and
Coding-
Search or Offer Perl Jobs  ----------------------------
http://jobs.perl.org
 
_______________________________________________
Boston-pm mailing list
Boston-pm@mail.pm.org
http://mail.pm.org/mailman/listinfo/boston-pm

Reply via email to