How to tell the last iteration in a foreach loop?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • meili100
    New Member
    • Sep 2008
    • 1

    How to tell the last iteration in a foreach loop?

    Code:
    foreach $key (keys (%hash)){
      print "$hash{$key}:";
    }
    The last element will also be followed by a ":" which is not what I want. Is there a way to tell when foreach loops to its last round, so that I can skip printing the last ":"? Thanks!
    Last edited by numberwhun; Sep 26 '08, 11:44 PM. Reason: Please use code tags!
  • numberwhun
    Recognized Expert Moderator Specialist
    • May 2007
    • 3467

    #2
    First, please use code tags, they are required.

    Second, can you provide a sample of the data so we can see what you are talking about?

    Regards,

    Jeff

    Comment

    • KevinADC
      Recognized Expert Specialist
      • Jan 2007
      • 4092

      #3
      already answered on tek-tips

      Code:
      print join(':', map{$hash{$_}} keys %hash);

      Comment

      • vikramkumar
        New Member
        • Mar 2008
        • 4

        #4
        for example assume i have an array i.e,
        Code:
        my @a = (1,2,3,4,5,6);
        
        for(my $i = 0;$i<$#a;$i++) {
                 print $a[$i];
        }
        Above for loop we r excluding last element to print;

        Comment

        • Ganon11
          Recognized Expert Specialist
          • Oct 2006
          • 3651

          #5
          That's because you have i<$#a - use i<=$#a instead.

          Better yet, use a foreach loop:

          [CODE=perl]for my $element (@a) {
          print $element;
          }[/CODE]

          Comment

          • KevinADC
            Recognized Expert Specialist
            • Jan 2007
            • 4092

            #6
            Originally posted by vikramkumar
            for example assume i have an array i.e,
            Code:
            my @a = (1,2,3,4,5,6);
            
            for(my $i = 0;$i<$#a;$i++) {
                     print $a[$i];
            }
            Above for loop we r excluding last element to print;

            Next time post a new thread.

            Comment

            Working...