in reply to a q-n-d csv_join function

Elegant. Some minor points:

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')

Replies are listed 'Best First'.
Re^2: a q-n-d csv_join function
by jwkrahn (Abbot) on Mar 02, 2009 at 01:44 UTC
    my @x is unnecessary - map copies on its own

    map in the example modifies $_ and @_ is an alias to the original array so you need the copy in order not to modify the original array passed to the subroutine.

Re^2: a q-n-d csv_join function
by perl5ever (Pilgrim) on Mar 02, 2009 at 01:42 UTC
    Re: my @x...

    if you do not pass the arguments as an array-ref, then something like my @x is necessary. Without the my @x =, perl will complain with:

    Modification of a read-only value attempted at ....

    unless these is another way around this problem...

      Hmmm... my test code (without my @x) didn't trigger that warning, but then I was passing arrays and not hard-coded lists of data. I think you would get that problem if you were calling csv_join('a', 'b', 'c') for example.

      Hard coded lists would also be a problem with the \@ prototype since it needs to take a reference to the array that was passed to csv_join('a','b','c') and hard coded lists don't have references. In fact, you would get something like this if the prototype is \@ and you called csv_join('a', 'b', 'c')

      Type of arg 1 to main::csv_join must be array (not constant item) at M +onks/QuickCsvJoin.pm line 33, near "'c') " Too many arguments for main::csv_join at Monks/QuickCsvJoin.pm line 33 +, near "'c') "

      If you need to make calls like csv_join('a','b','c') rather than csv_join(@aFields), then you will have to pass the array rather than just a reference to it. I've updated the original reply with the alternative. See above.

      Best, beth

Re^2: a q-n-d csv_join function
by GrandFather (Saint) on Mar 02, 2009 at 02:26 UTC
    Update: Re-added my @x. Thanks, jwkrahn. I had overlooked the effect of s/// on the elements of @_.

    which just goes to amplify my earlier comment concerning 'correctness and maintainability' ;-).


    True laziness is hard work