singular nouns if count equals 1, plural if 0 or >1
Pass a variable containing an integer representing the sum of something that has been counted to this subroutine and use $plur where an "s" would be needed if the count is 0 or >1.

example:

&pluralize($items); print "$items item$plur listed"; sub pluralize{ my $var = shift(@_); if($var==1){$plur=""} else {$plur="s"} }
various results:
0 items listed
1 item listed
2 items listed

Update: This topic is also covered in Perl Cookbook recipe 2.18. Printing Correct Plurals which has solutions using printf, Lingua::EN::Inflect, and (naughty) regexps.

Replies are listed 'Best First'.
Re: Pluralize nouns
by turnstep (Parson) on Dec 11, 2000 at 17:03 UTC

    A few notes:

    • "shift(@_)" can be written simply as "shift"
    • The subroutine should return a string, instead of setting a global variable. It's a good practice to get into, especially when you start messing with packages.
    • A return also allows the sub to be stuck directly into the program without using a variable (see the chad example below)
    • The ternary operator is cool. :)
    my $plur = &pluralize($items); print "$items item$plur listed"; print "I counted $chads vote", &pluralize($chads),"!\n"; sub pluralize($) { return shift==1 ? "" : "s"; }
Re: Pluralize nouns
by chipmunk (Parson) on Dec 11, 2000 at 20:35 UTC
    For more inflecting power than should exist in a single module, how about Lingua::EN::Inflect? It not only pluralizes nouns like 'cat' -> 'cats', it also handles nouns like 'basis' -> 'bases' and 'church' -> 'churches', as well as pronouns ('I' -> 'we'), adjectives, and verbs. Really, there's more to this module than I can summarize here (hint: the author is Damian Conway) -- just read the documentation! :)
Re: Pluralize nouns
by extremely (Priest) on Dec 11, 2000 at 13:58 UTC
    hmm, I always liked
    print "$item item". ($item==1 ? "" : "s"). " in the set\n";

    --
    $you = new YOU;
    honk() if $you->love(perl)

      Nice one! However, as my simplified example doesn't show, this snippet was written to handle pluralizing within here docs, hence the subroutine.

      thanks for the educational reply - epoptai

Re: Pluralize nouns
by I0 (Priest) on Dec 12, 2000 at 10:06 UTC
    for $item ( 0..3 ){ print "$item item",$item!=1&&"s","\n"; }