Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re: The longest word ....

by FamousLongAgo (Friar)
on Nov 12, 2002 at 03:33 UTC ( [id://212185]=note: print w/replies, xml ) Need Help??


in reply to The longest word ....


print join "\n", sort { length($b) > length($a) } split /\s+/, <DATA>;

But can anyone help me find a clever way to only print the words of maximum length?

Replies are listed 'Best First'.
Re: Re: The longest word ....
by sauoq (Abbot) on Nov 12, 2002 at 03:59 UTC

    Of course using sort just makes it too easy. :-)

    sub longest_words { my @W = sort { length($b) <=> length($a) } $_[0] =~ /\b(\w+)\b/g; grep length == length($W[0]), @W; }

    As long as you do it right, that is. You'll need to use <=> in your sort. Just testing for 'greater than' isn't sufficient.

    Update: A little golfing gets the sub down to 79 characters:

    sub longest_words { my@W=sort{length($b)<=>length($a)}$_[0]=~/(\w+)/g;grep length==length( +$W[0]),@W }

    -sauoq
    "My two cents aren't worth a dime.";
    

      # 1 2 3 4 5 6 7 #23456789_123456789_123456789_123456789_123456789_123456789_123456789_ +123456789 my@W=sort{length($b)<=>length($a)}$_[0]=~/(\w+)/g;grep length==length( +$W[0]),@W

      Untested code ahead

      # 1 2 3 4 5 6 7 #23456789_123456789_123456789_123456789_123456789_123456789_123456789_ +1 my@W=sort length$b<=>length$a,$_[0]=~/\w+/g;grep length==length$W[0],@ +W
      See, no parens :)

      But, since we're playing golf...

      # 1 2 3 4 #23456789_123456789_123456789_123456789_123 push@{$_[y///c]},$_ for+pop=~/\w+/g;@{+pop}

      - Yes, I reinvent wheels.
      - Spam: Visit eurotraQ.
      

      heh, stripping blanks off does no good for a real golf ;-) but the idea of skipping the additional hash ofc it' good :) wd. hehe, some golfing you could have done seeing that 'length' appears quite often in your routine ;-)

      --
      AltBlue.

        heh, stripping blanks off does no good for a real golf ;-)

        Sometimes whitespace is necessary so you should strip the unnecessary spaces when you are golfing.

        some golfing you could have done seeing that 'length' appears quite often in your routine ;-)

        Yes, it does. In each case, though, it is taking the length of something different: once for each of $a and $b in the sort, and once for each of $_ and $W[0] in the grep. So, I'm not sure what you point is. Feel free to share your improvements.

        -sauoq
        "My two cents aren't worth a dime.";
        

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://212185]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (6)
As of 2024-04-23 12:04 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found