I needed a function with the following properties: prefix_print(@list) should work exactly like print(@list), except that each line in the output should be prefixed by $prefix. For example, if $prefix is set to 'P', a call to prefix_print("A\nB","C\n") should print:
PA PBC

My first attempt went like this:

sub prefix_print { # Put $prefix in front my $outstr=join('',$prefix,@_); # If something follows a \n, insert $prefix $outstr =~ s/(\n)(?=.)/$1.$prefix/egs; print $outstr; }
This code works, as far I can see, but it requires the usage of a temporary variable, $outstr. Of course this is not really a problem, but being very fond of Perl's functional aspects (for instance, using split, map and so on), and - more out of curiosity than necessity - I was searching for an alternative solution, working without temporary variable and still simple enought to be understandable. Here is my attempt:
# Note: This is buggy sub prefix_print { # Turn arguments into a list of lines, and prepend # each with $prefix print( map { "$prefix$_" } join('',@_) =~ m/(.*(?:\n|$))/g ); }
This does NOT work, however, because if called as prefix_print('y'), it prints
PyPP
which suggests that my regular expression returns an array of three matches (one containing 'y', and two containing the empty string).

Could someone explain where these matches come from? Also, I would be glad to learn about any improvements for my code.

-- 
Ronald Fischer <ynnor@mm.st>

In reply to Can we do without auxiliary variable here? by rovf

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.