in reply to foreach loops

Here is one way:
use strict; my @names = ('rita', 'sue','bob', 'daisy'); $, = ' '; $\ = "\n"; foreach (0 .. $#names) { print @names[$_, $_+1]; }
Output:
rita sue sue bob bob daisy daisy

Replies are listed 'Best First'.
Re^2: foreach loops
by johngg (Canon) on Oct 07, 2006 at 23:25 UTC
    If warnings are switched on you will get an 'Use of uninitialized value ...' message once you get to the last time around the loop as print tries to access one more element than is in the array. This stops the warning.

    use strict; use warnings; my @names = qw{rita sue bob daisy}; $, = q{ }; $\ = qq{\n}; foreach (0 .. $#names) { print $_ == $#names ? $names[$_] : @names[$_, $_ + 1]; }

    Cheers,

    JohnGG

      Thank you everyone. I think I've strayed into the relms of perl magic. What are these operators called? I'd like to find out more about them

      $,

      $\

        They are not operators but variables. The $, is the string that gets printed between fields automatically, nothing by default. The $\ is what gets printed after allf fields, again nothing by default. If you set it to "\n", every print command will print a newline.

        All these nice variables can be found in the perlvar documentation.