Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks,

I am looking to see if there is a "foreach" technique for this. This is a "forced" example, so I am hoping it is clear ;-)

foreach (@data) { print "$_"; print "\t"; }
I don't want to print a tab at the end...is there a way to do this with a "foreach" loop? Maybe a "special" char that says I am at the end of the array? ie: print "\t" unless EOA

I can do this with other operators, but want to see if I am missing something with "foreach"

thanks !

Replies are listed 'Best First'.
Re: looping idiom
by theguvnor (Chaplain) on Mar 07, 2002 at 03:25 UTC
    I take it you don't want to

    print join ("\t", @data);

    so if you insist on using foreach, how about re-ordering your prints like this:

    print shift @data; foreach (@data) { print "\t"; print "$_"; }

    Shrug...

    Update: same caveat about references that japhy mentions applies to the above. I was assuming your array did not entail any complex data structures ;)

    Update 2: OK not exactly the same problem as japhy mentions, but if your @data array contains references you're gonna get ugly results ;) thanks for correcting me japhy

    ..Guv

Re: looping idiom
by japhy (Canon) on Mar 07, 2002 at 03:27 UTC
    This method is not guaranteed to work if your array contains references:
    foreach (@data) { print; print "\t" if \$_ != \$data[-1]; }

    _____________________________________________________
    Jeff[japhy]Pinyan: Perl, regex, and perl hacker, who'd like a (from-home) job
    s++=END;++y(;-P)}y js++=;shajsj<++y(p-q)}?print:??;

Re: looping idiom
by BeernuT (Pilgrim) on Mar 07, 2002 at 03:29 UTC
    another way is:
    print join("\t", @data);


    -bn
Re: looping idiom
by mrbbking (Hermit) on Mar 07, 2002 at 13:58 UTC
    Maybe this is a silly answer, but maybe it's not:
    foreach (@data) { print "$_"; print "\t"; } print "\b"; # backspace over the last tab
    If that wasn't silly, this certainly won't be...
    my $string; foreach( @data ){ $string .= "$_\t"; } chop( $string ); # not chomp, but chop. print $string;
    "Silly" is relative.
Re: looping idiom
by Sidhekin (Priest) on Mar 07, 2002 at 15:58 UTC

    The best suggestion I can give, if you want to play it real safe and don't want work on copies (in which case a while loop would have been more obvious):

    { my $i = 1; foreach (@data) { print "$_"; print "\t" unless $i == @data; } continue { $i++; } }

    The Sidhekin
    print "Just another Perl ${\(trickster and hacker)},"