Elegant. Some minor points:
- need to consider other types of whitespace, so
[ ,] => [\s,]
- passing a reference to an array is more efficient than passing the array - if you pass the array you will have to pass by reference each array member rather than just the single array reference. To preserve the calling syntax of csv_join(@someArray) use the prototype \@.
However, you can only use \@ if your parameters are arrays. If hardcoded lists are used as parameters, e.g. csv_join('a','b','c') instead of arrays, e.g. csv_join(@aFields), then you will need to use the version that passes the entire array. The \@ prototype would complain about extra parameters and failed attempts to take references of constant items.
- interpolating quotes unnecessary for ","
my @x is unnecessary - map copies on its own
- golf score (which shouldn't matter, but if you care) - use /.../ not m{...} and s{...}{...}
With revisions (using the \@ protoype)p>
sub csv_join(\@) {
join ',', map {s/"/""/g || /[\s,]/ ? qq{"$_"} : $_} (my @x=@{$_[0]});
}
With revisions (passing the entire array):
sub csv_join {
join ',', map { s/"/""/g || /[\s,]/ ? qq{"$_"} : $_} (my @x=@_);
}
Best, beth
Update: Re-added my @x. Thanks, jwkrahn. I had overlooked the effect of s/// on the elements of @_.
Update 2: Added an alternative if the function needs to be called with hard coded lists, e.g. csv_join('a','b','c')
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.