in reply to Re^3: Concatenate printing a string and array
in thread Concatenate printing a string and array

Rats - forgot the local.

All the more reason to use join().

Replies are listed 'Best First'.
Re^5: Concatenate printing a string and array
by johngg (Canon) on Jan 05, 2009 at 20:19 UTC

    I often use join but it can begin to get tedious if, for instance, you are printing more than one array using the same separator. Localising a change to the list separator then begins to simplify things, as in this rather contrived and silly example.

    use strict; use warnings; my @ladies = qw{ ann flo jen }; my @gents = qw{ bob pip tim }; print q{The ladies, (}, join( q{, }, @ladies ), q{), met the gents, (}, join( q{, }, @gents ), qq{).\n}; print qq{The ladies, (@{ [ join q{, }, @ladies ] }), }, qq{liked the gents, (@{ [ join q{, }, @gents ] }).\n}; print do{ local $" = q{, }; qq{The ladies, (@ladies), married the gents, (@gents).\n}; };
    The ladies, (ann, flo, jen), met the gents, (bob, pip, tim). The ladies, (ann, flo, jen), liked the gents, (bob, pip, tim). The ladies, (ann, flo, jen), married the gents, (bob, pip, tim).

    Cheers,

    JohnGG

      My own inclination is to see a statement like
          { local $" = 'foo';  print "array @ra values"; }
      as being more elegant and 'quiet' and to prefer it over a statement like
          print "array ", join('foo', @ra), " values";
      which just seems messy to me.

      This preference continues until I forget (as in my reply) to actually use the local built-in, or fail to properly specify the limiting scope, or forget that a change to a package variable will 'propagate' to any subroutines called within the limiting scope after the change is made.

      Then I realize that I have inflicted upon myself a headache, possibly a massive 3 A.M. headache, and I resolve not to localize $" (or any other package variable if I can help it) and to use join() instead, however messy.

      And I keep my resolution for a while, and then start backsliding.