Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extract every nth number

Tags:

perl

i want to extract every 3rd number ( 42.034 , 41.630 , 40.158 as so on ) from the file see example-

42.034  13.749  28.463  41.630  12.627  28.412  40.158  12.173  30.831  26.823
12.596  32.191  26.366  13.332  32.938  25.289  12.810  32.419  23.949  13.329

Any suggestions using perl script ?

Thanks, dac

like image 265
dac Avatar asked Dec 08 '25 01:12

dac


1 Answers

You can split file's contents to separate numbers and use the modulo operator to extract every 3rd number:

my $contents = do { local $/; open my $fh, "file" or die $!; <$fh> };    
my @numbers = split /\s+/, $contents;

for (0..$#numbers) {
    $_ % 3 == 0 and print "$numbers[$_]\n";
}
like image 191
Eugene Yarmash Avatar answered Dec 10 '25 14:12

Eugene Yarmash



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!