Preetham Kalakuntla
Preetham Kalakuntla

Reputation: 1

How can I get the last element of each line in perl?

I have to get the last element in each line. I am using perl..

 1.25.56.524.2
 2.56.25.254.3
 2.54.28.264.2

Upvotes: 0

Views: 914

Answers (3)

zb226
zb226

Reputation: 10500

I assume by last element you mean the last value separated by .. Have a look at this code:

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

Output:

2
3
2

Upvotes: 0

VCSEL
VCSEL

Reputation: 412

One possibility would be:

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

Upvotes: 0

choroba
choroba

Reputation: 241858

Just split each line on a dot, last element has the index -1:

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

Upvotes: 4

Related Questions