#!/usr/bin/perl use strict; use warnings; # ^-- Just do it. my $Gene = 'ds_chY.xml'; my $filename = 'ID.txt'; open my $fh_i, '<', $Gene or die "Cannot open the file '$Gene': $!"; open my $fh_o, '>', $filename or die "Could not open file '$filename' $!"; # ^-- use the same style of open() and error message # for both file operations # (I like to put chained and/or conditionals on the next line.) print {$fh_o} "RS_SNPs\tsubSnpClass\n"; # ^- use braced filehandles in order to make it explicit we're # writing to a file handle # either use explicit variable for looping: while (my $line = <$fh_i>) { $line =~ s/^\s+//; # this is probably irrelevant # don't write to file immediately - wait a bit my ($ssId, $subSnpClass); if ( $line =~ /ssId=["](\S*)["]\s/ ) { # regexp optimization $ssId = $1; # -> no need to s/// and chop } if ( $line =~ /subSnpClass=["](\S*)["]/ ) { $subSnpClass = $1; } # ...in order to perform a small sanity check if (defined $ssId and defined $subSnpClass) { print {$fh_o} "$ssId\t$subSnpClass\n"; } elsif (not defined $ssId and not defined $subSnpClass) { # nothing } else { print "Data inconsistency detected in line $line\n"; } } # ... or use implicit variable $_: while (<$fh_i>) { s/^\s+//; my ($ssId, $subSnpClass); if ( /ssId=["](\S*)["]\s/ ) { $ssId = $1; } if ( /subSnpClass=["](\S*)["]/ ) { $subSnpClass = $1; } if (defined $ssId and defined $subSnpClass) { print {$fh_o} "$ssId\t$subSnpClass\n"; } elsif (not defined $ssId and not defined $subSnpClass) { # nothing } else { print "Data inconsistency detected in line ", $_, "\n"; } }