Richard Lee wrote:
While reading perl cookbook, I came to page 94 and having a hard time
understanding this particular phrase
my $sepchar = grep( /,/ => @_ ) ? ";" : ",";
I recognize the ternary operator and grep but I am not sure how they are
forming the meaning together.
I thought grep needed lists to work on ? and grep(/,/ => @_), I am not
sure where it's getting the list from
my @results = grep EXPR, @input_list;
my $count = grep EXPR, @input_list;
And I also don't understand what ";" is doing in the ternary operator??
Inside of a subroutine the @_ contains the arguments supplied to that
subroutine so the list comes from @_. grep() is used in boolean context
so if any of the contents of @_ contains a comma then ";" is assigned to
$sepchar else if there are no commas then "," is assigned to $sepchar.
I think I understand the rest of the program though..
Can someone help me out please?
thank you.
-------------------- Complete program --------------------------
#!/usr/bin/perl -w
use strict;
my @lists = (
[ 'just one thing' ],
[ qw(Mutt Jeff) ],
[ qw(peter Paul mary) ],
[ 'To our parents', 'Mother Theressa', 'God' ],
[ 'pastrami', 'ham and cheese', 'peanut butter and jelly', 'tuna' ],
[ 'recycle tired, old phrases', 'ponder big, happy thoughts' ],
[ 'recycle tired, old phrases',
'ponder big, happy thoughts',
'sleep and dream peacefully' ],
);
for my $aref ( @lists ) {
print "The list is: ". commify_series( @$aref ) . ".\n";
}
sub commify_series {
my $sepchar = grep( /,/ => @_ ) ? ";" : ",";
( @_ == 0 ) ? ''
: ( @_ == 1 ) ? $_[0]
: ( @_ == 2 ) ? join(" and ", @_ )
: join("$sepchar ", @_[0 .. ($#_-1) ], "and $_[-1]" );
}
If @_ is empty then return '' else if @_ contains one element return
that element else if @_ contains two elements then join them both with
the string " and " else join the first through second to last, and the
last prepended with the string "and ", together using the string
"$sepchar ".
John
--
Perl isn't a toolbox, but a small machine shop where you
can special-order certain sorts of tools at low cost and
in short order. -- Larry Wall
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/