Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: Print the line with the largest number from standard input

by BillKSmith (Monsignor)
on Jul 23, 2019 at 20:54 UTC ( [id://11103251]=note: print w/replies, xml ) Need Help??


in reply to Print the line with the largest number from standard input

The use of 'sort' to find a max is always overkill, but can be convenient if efficiency is not an issue. In your case, you probably want 'nsort_by' from the module List::SomeUtils instead of the native 'sort'.

You should be more explicit in describing what you mean by 'number'. Your code finds only continuous strings of decimal digits. (Note: This ignores negative signs. e.g. -124 > 123)

An easy way to find the maximum of the numbers on one line is to use the function 'max' from List::Util

>type SSSufe.pl use strict; use warnings; use List::Util qw(max); use List::SomeUtils qw(nsort_by); my @lines = <DATA>; print ((nsort_by { biggest_on_line($_) } @lines)[-1]); sub biggest_on_line { my $line = shift; my @nums = $line =~ /(\d+)/g; return max @nums; } __DATA__ Hello, i'm 18 1 this year is 2019 1 1 2 3 - 4 >perl SSSufe.pl 1 this year is 2019 1
Bill

Replies are listed 'Best First'.
Re^2: Print the line with the largest number from standard input
by haukex (Archbishop) on Jul 25, 2019 at 20:14 UTC

    Nitpick: Because max returns undef when the list is empty (= there is a line with no digits), this code will generate "uninitialized" warnings in that case.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (7)
As of 2024-04-25 11:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found