Hello Helan
Too be frank: Your posted coded looks like you cobbled it together without really understanding what you're doing. I took the liberty to clean it up somewhat. Request: Just have a look at it and see what could be done differently. The provided code is making some fundamental assumptions about your XML-format and works with the provided input - but I really, really recommend using a true XML-Parser instead.
#!/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"; } }
(The second while loop is useless, because there's no more stuff to be read. It's just an example how the loop could be written in a different manner.)
Please do NOT use:
while (<$fh_i>) { if ($_ =~ ...) ...
...because it's a bit like wearing your pants backwards. Sure you can do it and it keeps your legs warm, but everyone will laugh at you behind your back.
In reply to Re: Print multiple value from file
by Monk::Thomas
in thread Print multiple value from file
by Helan_Ahmed
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |