Operating System - HP-UX
1829594 Members
1732 Online
109992 Solutions
New Discussion

How to find the longest argument in a list - ksh? perl?

 
SOLVED
Go to solution
A. Daniel King_1
Super Advisor

How to find the longest argument in a list - ksh? perl?

Hi, folks.

I am looking for the most efficient answer to this question:

How does one find the longest argument in a list?

Minimum code and speed count. I came up with this ksh snip:

list="abc123 abc1234 abc12345"
stdlen=0
for item in $list
do
len=$(echo $item | wc -c)
[ $len -gt $stdlen ] && stdlen=$len
done
echo $stdlen

This seems to report the real max-length + 1.

I'm certain that you gurus know a quicker/better way to do this. perl & awk suggestions welcome.
Command-Line Junkie
5 REPLIES 5
James R. Ferguson
Acclaimed Contributor
Solution

Re: How to find the longest argument in a list - ksh? perl?

Hi Daniel:

In lieu of using 'wc' use the shell builtin :

len=${#item}

Hence your script becomes:

list="abc123 abc1234 abc12345"
stdlen=0
for item in $list
do
len=${#item}
[ $len -gt $stdlen ] && stdlen=$len
done
echo $stdlen

Regards!

...JRF...
Rodney Hills
Honored Contributor

Re: How to find the longest argument in a list - ksh? perl?

Here's a short perl routine-

@list=qw/abc123 abc1234 abc12345/;
$stdlen=length($_) > $stdlen ? length($_) : $stdlen foreach @list;
print "$stdlen\n";

HTH

-- Rod Hills
There be dragons...
Caesar_3
Esteemed Contributor

Re: How to find the longest argument in a list - ksh? perl?

Hello!

Where you calculate the length use this:
len=$#item

in $len you will have the size on $item

Caesar
James R. Ferguson
Acclaimed Contributor

Re: How to find the longest argument in a list - ksh? perl?

To Caesar:

You seem to have a habit of providing *identical* answers as others have already posted, often *hours before*. Why is that?

...JRF...
Jordan Bean
Honored Contributor

Re: How to find the longest argument in a list - ksh? perl?


If you want the argument itself, try this:

perl -e 'print @{[sort { length($b) <=> length($a) } @ARGV]}[0],"\n";'