> -----Original Message-----
John W. Krahn [mailto:[EMAIL PROTECTED]]
> On Tuesday 19 November 2002 15:50, Selector, Lev Y wrote:
> >
> > Simple question:
> > Is there a more elegant way to express this:
> > an array of names is converted into a comma-separated list.
> > if the list gets to long - limit it and add ", etc." at the end.
> >
> > $str = join ', ', @names;
> > if (length($str)>90) {
> > ($str = substr($str,0,90)) =~ s/,[^,]*$/, etc./;
> > }
>
> my $len = 89;
> my $str = join ', ', @names;
>
> $str =~ s/(.{0,$len},).*/$1 etc./;
>
Although this is a nice development of the original, it didn't press my own
"elegance button".
IMHO both of these are very rude to $str by making it receive data it never
wanted. This is then followed by an half hearted apology ("oh sorry guv'nor,
didn't see you there") to pick up the pieces. Indeed, some fool could give
us @names with 1e10 elements and we'd churn for several microfortnights just
to mung the first 90 bytes or so ("now who's sorry then"). More importantly,
perhaps, this method introduces a bug if any of @names were to contain any
strings matching /, /. Consider if @names
@names=(
"Bartlett, Miss Charlotte",
"Beebe, The Rev Arthur",
"Emerson, Mr George",
"Honeychurch, Miss Lucy"
);
d:\>test.pl
Bartlett, Miss Charlotte, Beebe, The Rev Arthur, Emerson, Mr George,
Honeychurch, etc.
Then poor Lucy's christian name becomes "etc", when I think she'd prefer not
to be mentioned at all.
Here's my slightly more elegent version where our first 90 bytes are treated
with the respect they deserve. It even copes with the case were $names[0] is
more than 90 bytes.
#We must add 2 for the "' " that we will unnecessarily allow for in the
first iteration
my $capacity=90+2;
my @guest_list;
for my $name (@names) {
if ( 0 > ($capacity -= 2 + length($name)) ) {
# I'm sorry sir your name doesn't seem to be on the guest
list
push @guest_list, "etc.";
last
} else {
# Welcome madam, enjoy the show.
push @guest_list,$name
}
}
$str = join ", ", @guest_list;
No if I can only force this into iambic pentameter I'd be well chuffed.
Ka kite ano,
Alistair
-----------------------------------------------------------------------
Registered Office:
Marks & Spencer p.l.c
Michael House, Baker Street,
London, W1U 8EP
Registered No. 214436 in England and Wales.
Telephone (020) 7935 4422
Facsimile (020) 7487 2670
www.marksandspencer.com
Please note that electronic mail may be monitored.
This e-mail is confidential. If you received it by mistake, please let us know and
then delete it from your system; you should not copy, disclose, or distribute its
contents to anyone nor act in reliance on this e-mail, as this is prohibited and may
be unlawful.
The registered office of Marks and Spencer Financial Services PLC, Marks and Spencer
Unit Trust Management Limited, Marks and Spencer Life Assurance Limited and Marks and
Spencer Savings and Investments Limited is Kings Meadow, Chester, CH99 9FB.