in reply to Format a list with commas and "and"

I was always taught that the correct way of printing lists like that was "A, B, C and D" (i.e. no comma before the "and"). If your English teacher was like mine then this version will work better for you:

sub and_a_list { if (@_ > 2) { join(", ", @_[0..$#_-1]) . " and $_[-1]" } elsif (@_ > 1) { "$_[0] and $_[1]" } elsif (@_ > 0) { $_[0] } else { "" } }
--
<http://www.dave.org.uk>

European Perl Conference - Sept 22/24 2000, ICA, London
<http://www.yapc.org/Europe/>

Replies are listed 'Best First'.
RE: RE: Format a list with commas and
by tye (Sage) on Aug 24, 2000 at 19:03 UTC

    That particular lie was propogated by newspaper publishers who thought they could save millions by dropping all those "extra" commas. Leaving the last commas off makes for a lot more ambiguity. Unfortunately, many academics got convinced that if newspapers write that way it must be a good idea.

    My favorite breakfasts are bacon and eggs, blueberry muffins, and sausage and biscuits. Take one, two or three times daily.

            - tye (but my friends call me "Tye")
      Thanks for that little bit of brain lint.
      I always "corrected" myself. I wondered why it never looked
      right to me.
Re: Format a list with commas and
by Abigail-II (Bishop) on Oct 02, 2002 at 10:46 UTC
    If you don't want that comma, you can do without the cases:
    sub list { join ", " => @_ [0 .. $#_ - 2], join " and " => @_ [grep {$_ >= 0} $#_ - 1, $#_] }

    Abigail

      sub list { join(" and ", reverse grep defined && length, pop @_, join(", ", @ +_)) }

      Makeshifts last the longest.