如何获取perl中每行的最后一个元素?

时间:2016-10-31 09:09:57

标签: perl

我必须得到每一行的最后一个元素。我正在使用perl ..

 1.25.56.524.2
 2.56.25.254.3
 2.54.28.264.2

3 个答案:

答案 0 :(得分:4)

点上的每一行只有split,最后一个元素的索引为-1:

print +(split /\./)[-1] while <>;

答案 1 :(得分:0)

我假设最后一个元素是指由.分隔的最后一个值。看看这段代码:

use strict;
my @last_values;                        # UPDATE: initialize array
for my $line (<DATA>) {                 # read line by line
    chomp $line;                        # remove newline at the end
    my @fields = split '\.', $line;     # split to fields
    my $last = pop @fields;             # get last field
    print $last."\n";
    push @last_values, $last;           # UPDATE: store last field in array 
}

__DATA__
1.25.56.524.2
2.56.25.254.3
2.54.28.264.2

输出:

2
3
2

答案 2 :(得分:0)

一种可能性是:

use strict;
use warnings;

my @Result;                 # Array holding the results

while (<DATA>)              # whatever you use to provide the lines...
{
  chomp;                    # good practice, usually necessary for STDIN
  my @Tokens = split(/\./); # assuming that "." is the separator
  push( @Result , $Tokens[-1] );
}

__DATA__
1.25.56.524.2
2.56.25.254.3
2.54.28.264.2