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

Sometimes I code like this:
my @lines=qw(this that the other); my $result= join("\n", @lines)."\n";
I need to join an array, and I also need to append the string used in the join to the end of the string. This bothers me because I sense that I am missing a better, simple way to do it. What am I missing?

In this example I am joining with newline but often I need to join and append with a different string.

Suggestions for ludicrously overdone CPAN modules are also welcome!

It should work perfectly the first time! - toma

Replies are listed 'Best First'.
Re: Join and append to last element?
by jand (Friar) on Mar 12, 2003 at 08:09 UTC

    Just add an empty string at the end of the list of things to join:

    my $result = join("\n", @lines, "");
Re: Join and append to last element?
by PodMaster (Abbot) on Mar 12, 2003 at 09:19 UTC
    :D
    my @lines = 1..3; my $result = do { local $" = "\n"; "@lines\n" }; die $result;


    MJD says you can't just make shit up and expect the computer to know what you mean, retardo!
    I run a Win32 PPM repository for perl 5.6x+5.8x. I take requests.
    ** The Third rule of perl club is a statement of fact: pod is sexy.

Re: Join and append to last element?
by BrowserUk (Patriarch) on Mar 12, 2003 at 08:14 UTC

    Whether it is in anyway 'better' I doubt, but you could do

    my @lines=qw(this that the other); my $result= join("\n", @lines,'');

    Hey! Maybe I should wrap that up in Data::Algorithm::Join::Plus::One :)


    Examine what is said, not who speaks.
    1) When a distinguished but elderly scientist states that something is possible, he is almost certainly right. When he states that something is impossible, he is very probably wrong.
    2) The only way of discovering the limits of the possible is to venture a little way past them into the impossible
    3) Any sufficiently advanced technology is indistinguishable from magic.
    Arthur C. Clarke.
Re: Join and append to last element?
by nite_man (Deacon) on Mar 12, 2003 at 08:12 UTC
    You can use a perl function map:
    my @lines=qw(this that the other); my $result=''; map { $result .= $_ ."\n" } @lines;
    
    ====>
    Mice were crying and stinging but went on nibbling the cactus ... 
                                                  ( The facts of life )
                                                                  <====
    
    

      That's better worded using 'for'. That is not how you use map. This is your idea reworded to not be so silly:

      $result .= "$_\n" for @lines;

      Seeking Green geeks in Minnesota

      Using map() just for side effects without good reason is often considered bad form. I'm sure my earlier suggestion is more efficient, but if you prefer using map(), I would do something like this:
      my $result = join("", map("$_\n", @lines));