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

Hi All, I have a file with the structure as follows:

xxxxxx: 0
yyyyyy: 6
zzzzzz: 5

and so on and so forth. I want to copy the numbers(which are the last characters of each line ) to an array. How can I do this in perl? Thanks a lot for your help

Replies are listed 'Best First'.
Re: Last Character into Array
by BrowserUk (Patriarch) on Apr 26, 2011 at 02:09 UTC

    If you really mean just the last non-newline character:

    #! perl -slw use strict; my @array = map{ chomp; chop } <DATA>; __END__ xxxxxx: 0 yyyyyy: 6 zzzzzz: 5

    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
Re: Last Character into Array
by wind (Priest) on Apr 26, 2011 at 01:35 UTC
    use strict; use warnings; my $file = 'foo.txt'; open my $fh, $file or die "$file: $!"; my @array; while (<$fh>) { push @array, $1 if /(\d+)$/; } close $fh; print "@array\n";
      The first digits if found in the first field would get transferred into the array instead of the second field. oops just noticed the "$" in the regexp

      One world, one people

Re: Last Character into Array
by anonymized user 468275 (Curate) on Apr 26, 2011 at 13:15 UTC
    Using the most fault tolerant regexp I can think of:
    my @array = (); open my $fh, "file.ext" or die $!; LINE: while ( <$fh> ) { chomp; $_ and next LINE; if ( /\S+\s*\:\s*(\d+)/ ) { push @array, $1; } else { die "unexpected data format at line $.:\n$_\n"; } } close $fh;

    One world, one people