Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

How would I print the last element of a loop?
If I run a code and go trough a file and found 5 numbers hor can I print the larger number?
Thanks

Title edit by tye

  • Comment on How would I print the last element of a loop?

Replies are listed 'Best First'.
Re: Looping
by tachyon (Chancellor) on Apr 02, 2004 at 16:01 UTC

    Sounds like homework.

    print $array[-1]; my $last; for ( @array ) { $last = $_ }; print $last; my $big = -999999999; while(<FILE>) { chomp; $big = $_ if $_ > $big }; print $big;

    cheers

    tachyon

Re: Looping
by Limbic~Region (Chancellor) on Apr 02, 2004 at 16:05 UTC
    Anonymous Monk,
    How would I print the last element of a loop?
    print "$array[-1]\n"; # If you mean last element of array my $last = keys %hash; my $counter = 0; for my $key ( keys %hash ) { $counter++; print "$hash{$key}\n" if $counter == $last; } # If you mean determine if this is last item in loop
    If I run a code and go trough a file and found 5 numbers hor can I print the larger number?
    use Scalar::Util 1.10 'looks_like_number'; use List::Util 'max'; my @numbers; while ( <FILE> ) { chomp; push @numbers , $_ if looks_like_number( $_ ); } print max(@numbers), "\n";
    I would highly recommend you take a look at How do I post a question effectively?. You can find it and other helpful information at the PerlMonks FAQ.

    Cheers - L~R

Re: Looping
by Roy Johnson (Monsignor) on Apr 02, 2004 at 15:59 UTC
    Typically, you would use a variable to keep track of the largest, as you read through the file.

    If you want to print only the last line of a file, you could do

    while (<>) { print if eof }

    The PerlMonk tr/// Advocate
Re: How would I print the last element of a loop?
by Anonymous Monk on Apr 02, 2004 at 18:24 UTC

    If this is homework and "spaceship operator" is allowed...to get the larger number:

    @nums = (57, 113, 25, 76, 712, 13, 3); foreach (sort {$a <=> $b} @nums) { $larger = $_ } print "The numbers: @nums\n\nlarger=$larger\n";

      Erm, you've combined an O(N log N) sort with an O(N) iteration (not to mention always performing N assignemnts); whereas a simple iterative scan will always be just O(N) and will at worst perform N assignments on an already sorted list. Not exactly the most efficient way to find it . . .

      Update: . . . then again maybe we need more answers like this to discourage homework questions. :)