roserose
roserose

Reputation: 1

perl sorting - how to output the row number matched data fields

I have a file that looks like this:

ID
1
3
3
6
7
1
1
16
X

I want to loop through for each line and if it matches 1, extract the row number. In my code it works for two digit numbers (11, 12, 13...) but for single digit it does not work. It produces an empty output file. i tried with the substring substr($data[$j],0 ); to catch the whole string in the field but it doesn't work at all then. How can I fix this?

print "\nRead list file in\n";
open(FILE, "list.txt") or die("Unable to open file");
my @data = <FILE>; # this is the whole filestored
my $data_size = @data;

 ##name the input
print "Which number do you want to sort out?";
my $input = <>;
chomp($input);
print "\n";


 ## for each line of the file get the column numbers to cut based on input number
open OUTPUT, ">$input.txt";  
print OUTPUT "0 \n";

for (my $j =0; $j < $data_size; $j++){

    my $match = substr($data[$j],0,2);
    if ($match eq $input){
        print OUTPUT "$j\n";
    }       
}
print "data is in the files ";

Upvotes: 0

Views: 145

Answers (2)

Borodin
Borodin

Reputation: 126752

The immediate problem is that the date you have read into @data has newlines at the end of each line, while you are using chomp on the string input from the terminal so that can never match.

If you are matching a two-digit number then substr $data[$j], 0, 2 will remove the newline for you, but anything short remains untouched.

You could just chomp @data, but there are another few details that could be improved, so this is a rewrite that should be useful

use strict;
use warnings;

print "\nRead list file in\n";
open my $in_fh, '<', 'list.txt' or die "Unable to open 'list.txt' for input: $!";
chomp(my @data = <$in_fh>);
close $in_fh;

print "Which number do you want to sort out_fh?";
chomp(my $input = <>);
print "\n";

open my $out_fh, '>', "$input.txt" or die "Unable to open '$input.txt' for output: $!";
print $out_fh "0 \n";

my $found;

for my $j (0 .. $#data) {
  my ($match) = $data[$j] =~ /(\d+)/;
  next unless $match;
  if ($match == $input) {
    print $out_fh "$j\n";
    $found = 1;
  }
}
print "Data is in the files\n" if $found;

Upvotes: 0

Mark Setchell
Mark Setchell

Reputation: 207798

I think you need to chomp() the array @data after you read it in to remove linefeeds, like this:

print "\nRead list file in\n";
open(FILE, "list.txt") or die("Unable to open file");
my @data = <FILE>; # this is the whole filestored

chomp @data;

Upvotes: 1

Related Questions