0

I have a dataset like this:

10001;02/07/98;TRIO;PI;M^12/12/59^F^^SP^09/12/55

;;;;;M1|F1|SP1;11;10;12;10;12;11;1.82;D16S539

;;;;;M1|F1|SP1;8;8;8;8;10;8;3.45;D7S820

;;;;;M1|F1|SP1;14;12;12;11;14;11;1.57;D13S317

;;;;;M1|F1|SP1;12;12;13;12;13;8;3.27;D5S818

;;;;;M1|F1|SP1;12;12;12;12;12;8;1.51;CSF1PO

;;;;;M1|F1|SP1;8;11;11;11;11;8;1.79;TPOX

;;;;;M1|F1|SP1;6;9;9;6;8;6;1.31;TH01

I'm trying to extract the last element of the lines which does not start with a number, i.e. all lines except the first one. I want to put these values inside an array called @markers.

I'm trying that by the following code:

#!usr/bin/perl
use warnings;
use strict;

open FILE, 'test' || die $!;

while (my $line = <FILE>) {

    my @fields = (split /;/), $line;

    if ($line !~ m/^[0-9]+/) {

    my @markers = splice @fields, 0, @fields - 1;

    }
}

But that does not work. Can anyone help please? Thanks

2 Answers 2

2
  • You create a new variable named @markers every pass of the loop.
  • my @fields = (split /;/), $line; means (my @fields = (split /;/, $_)), $line;. You meant my @fields = (split /;/, $line);
  • 'test' || die $! is the same as just 'test'.

use strict;
use warnings;

open my $FILE, '<', 'test'
   or die $!;

my @markers;
while (<$FILE>) {
    chomp;
    next if /^\s*\z/;  # Skip blank lines.
    my @fields = split /;/;
    push @markers, $fields[-1]
        if $fields[0] eq '';
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you guys very much. Only one last question: how can I use this array to initialize a hash, using the array as keys and all the values = zero?
my %hash = map { $_ => 0 } @markers; but you could avoid the array entirely by using $hash{$fields[-1]} = 0; instead of push @markers, $fields[-1];.
0

You aren't using function split() correctly. I have fixed it in the code below and printed the values:

#!/usr/bin/perl
use warnings;
use strict;

open FILE, 'test' || die $!;

while (my $line = <FILE>) {

    my @fields = split( /;/, $line);

    if ($line !~ m/^[0-9]+/) {

        print "$fields[-1]";
#    my @markers = splice @fields, 0, @fields - 1;

    }
}

3 Comments

Above answer is better, I was working on the solution while someone else beat me to the answer.
Thank you guys very much. Only one last question: how can I use this array to initialize a hash, using the array as keys and all the values = zero?
You could use a foreach loop to assign the hash key and set value to zero.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.