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

Hi,

I have a simple, general question regarding a real small issue that bothers me:

I'm printing a list of elements on the fly, so I don't have prior knowledge about the number of printed elements. I want a simple format where the elements are separated by a comma (elem1, elem2...) or something similar. Now, if I use a simple loop like:

while(elements to check) { if (elem should be printed) { print elem . "," } }
I get a comma after the last element...

I know this sounds quite stupid, but is there a way to handle this?

Replies are listed 'Best First'.
Re: printing lists...
by Ratazong (Monsignor) on Jul 27, 2010 at 10:39 UTC

    You don't know the last element ... but you know the first. Using that knowledge, you can enhance your logic as follows:

    my $first = 0; # a flag to remember the first +element while(elements to check) { # * if (elem should be printed) { # * if ($first == 0) { $first = 1; } # don't print a comma before th +e first element else { print ","; } # print a comma print elem # * } }

    HTH, Rata

    Update: marked the pseudocode of the original poster with # * to reduce confusion
      Clever approach. Minor glitch in implementation.
      Update: that should be "glitch in my interpretation." Neither Ratazong's nor OP's data is necessarsarily formatted as I did it.

      my $first=0; while (<DATA>) { chomp ($_); my $element = $_; if ($first == 0) { $first = 1; # don't print a comma before the first element } else { print ","; # print a comma } print $element; } print "\n"; __DATA__ foo bar blivitz this is a line 1 2 a b cde

      Ratazzong produces:

      foo ,bar ,blivitz ,this is a line ,1 ,2 ,a ,b ,cde

      instead of (what I understand to be) OP's desire:

      foo,bar,blivitz,this is a line,1,2,a,b,cde
Re: printing lists...
by cdarke (Prior) on Jul 27, 2010 at 12:01 UTC
    my @elements = qw(The quick brown fox); local $, = ','; print @elements;
    Gives:
    The,quick,brown,fox
    Or you could use $" with interpolation.
Re: printing lists...
by johngg (Canon) on Jul 27, 2010 at 13:09 UTC

    Some examples.

    $ perl -E ' > @arr = qw{ apple pear plum }; > say @arr; > say qq{@arr}; > say do { > local $" = q{, }; > qq{@arr}; > }; > say join q{, }, @arr; > print join qq{\n}, @arr; > say q{OOPS!! no trailing newline :-(}; > print join qq{\n}, @arr, q{}; > say q{BETTER!! empty string joined on the end :-)};' applepearplum apple pear plum apple, pear, plum apple, pear, plum apple pear plumOOPS!! no trailing newline :-( apple pear plum BETTER!! empty string joined on the end :-) $

    Cheers,

    JohnGG

Re: printing lists...
by Anonymous Monk on Jul 27, 2010 at 10:24 UTC