There are several things that look a bit funny in your code. First, you're declaring @age within your while loop, so it never accumulates more than one line of your input file (that's fine since we don't really need it, but just be aware of the scoping issue). Then you split $line into 3 variables, but there are only 2 listed in the input example you gave, which means the last one ($personage) will be undefined. You then attempt to split the value of $personage on newlines, and put the result into @age.

If all you want is a list of ages (and not the associated names), you can do something like this:

use strict; use warnings; my @ages; while( my $line = <DATA> ) { chomp $line; # get rid of the pesky newline my ( $name, $age ) = split( ', ', $line ); # name isn't used now push( @ages, $age ); # add each $age to the @ages array } @ages = sort { $b <=> $a } @ages; print join( "\n", @ages ); __DATA__ Charley, 34 Sam, 3 Lucy, 18
If you want to retain the person's name with each age, I'd recommend using a hash (name => age) or, if names are not unique, an array of arrays ([name, age], [name, age]...). The sort routine will change depending on the data structure you use (see perldsc and sort).

HTH

Update:TedYoung's solution has a more robust pattern for split. I was assuming your data was well-formed, where fields were separated by a comma and a single space. If that is not the case, a regex should be used.


In reply to Re: Using file handles by bobf
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.