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:
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: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 does NOT work, however, because if called as prefix_print('y'), it prints# 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 ); }
which suggests that my regular expression returns an array of three matches (one containing 'y', and two containing the empty string).PyPP
Could someone explain where these matches come from? Also, I would be glad to learn about any improvements for my code.
In reply to Can we do without auxiliary variable here? by rovf
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |