sevonchan
sevonchan

Reputation: 75

Perl: print the line with the largest number from standard input

i'm very new to Perl and I've been trying to implement a function that print out the line with the largest number from the standard input. For example, If the input is:

Hello, i'm 18

1 this year is 2019 1

1 2 3 - 4

The output should be: 1 this year is 2019 1

And secondly, I would like to know what does $line =~ /-?(?:\d+.?\d*|.\d+)/g mean?

The following is what I've tried, it is not working and I hope someone could fix it for me. I'm struggling with filtering out random characters but leaving out the digit.

Is it necessary to push the largest number onto an array? Is there any way that once we could do this in one step?

#!/usr/bin/perl -w

while ($lines = <STDIN>){
    @input = $lines =~ /\d+/g;
    if (!@input){
    } else {
        $largest_number = sort {$a <=> $b} @input[0];
        push(@number, $largest_number);
    }
}
    if (!@number){
    }else{
        print $largest_number;
    }

Upvotes: 1

Views: 687

Answers (1)

choroba
choroba

Reputation: 241988

@input[0] returns just the first value from the array. You probably want to use @input instead - but this way you'd get the numbers from one line sorted. Also, you need to store the whole line somewhere in order to be able to display it later.

Here's how I would do it:

#!/usr/bin/perl
use warnings;
use strict;

my @max;
while (my $line = <>) {
    my @numbers = $line =~ /\d+/g;
    for my $n (@numbers) {
        if (! @max || $n > $max[0]) {
            @max = ($n, $line);
        }
    }
}

print $max[1] if @max;

The @max array stores the largest number in $max[0], while $max[1] keeps the whole line. You just compare each number to the largest one, there's no need to search for the maximum for each line.

To store all the lines containing the largest number, change the loop body to

        if (! @max || $n > $max[0]) {
            @max = ($n, $line);
        } elsif ($n == $max[0]) {
            push @max, $line;
        }

and the last line to

print @max[ 1 .. $#max ] if @max;

Upvotes: 4

Related Questions