Hi,

I don't think I understand your code... for each line in the file, you are splitting on a comma, expecting a name, city, and age. But, in your sample data, you only have name followed by age. If your sample data is a sample of your log file, then let's try this code:

use strict; my $file = "input.log"; my @sorted_ages; open (IN, $file) or die "Couldn't open file '$file': $!"; while (my $line = <IN>) { chomp($line); my ($name, $age) = split(/,\s*/, $line); push @sorted_ages, $age; } close (IN); @sorted_ages = sort { $b <=> $a } @sorted_ages;

So, this goes: Split each line in the file by a comma* which will return the name, followed by the age. Then put that age in the array @sorted_ages. At the very end of the loop, we sort @sorted_ages.

* the \s* in the split makes sure to take up any spaces between the comma and age. We also chomp the line before splitting to remove the trailing new line.

If you follow so far, we can simplify this code a bit:

use strict; my $file = "input.log"; my @sorted_ages; open (IN, $file) or die "Couldn't open file '$file': $!"; @sorted_ages = sort { $b <=> $a } map { # Use a regex to find the age # ^ = start of string, # .*?, = skips to the first comma # (\d+) = capture a number into $1 /^.*?, (\d+)/; $1 } <IN>; close (IN);

Ted Young

($$<<$$=>$$<=>$$<=$$>>$$) always returns 1. :-)

In reply to Re: Using file handles by TedYoung
in thread Using file handles by gitarwmn

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.