Re: parsing script duplication of lines issue, please advise

Re: parsing script duplication of lines issue, please advise

am 21.07.2011 15:16:23 von Shlomi Fish

Hi Nathalie,

On Thu, 21 Jul 2011 12:00:57 +0100
Nathalie Conte wrote:

> HI,
> I want to create a simple script where I am parsing a file and writing
> only the lines where I can find a certain value in a new output file
> this is my Infile format: workable example attached
> I want to keep only the lines where there is a 1 not the ones with -1,
> there are 10 in this example and when I produce my outfile it is 20
> lines long! They are duplicated and I am not sure why, I would
> appreciate any advise. the example infile attached contain 50 and
> produce a outfile of 100...

Some comments on your code.

>
>
> ####this is my script
> #!/software/bin/perl
> use warnings;
> use strict;
>

That's very good.

>
>
>
> my $file="./infile.txt";
>
> open( IN , '<' , $file ) or die( $! );
> open(OUT, ">>outfile.txt");

1. Always use three-args open.

2. Always check for open's return.

3. Use lexical file handles instead of "IN"/"OUT"/etc.:

http://perl-begin.org/tutorials/bad-elements/

>
>
> while (){

1. Don't iterate using $_ because it can easily get devastated.

2. You probably want chomp() here:

http://perldoc.perl.org/functions/chomp.html

without it you'll have a trailing newline.

>
> my @line=split(/\t/);

>
> if($line[3]==-1) {
> print OUT $line[0],"\t",$line[1],"\t",$line[2],"\t",$line[3],"\n";
> }

This can be written more succinctly as:

print {$out_fh} join("\t", @line[0 .. 3]), "\n";

Regards,

Shlomi Fish

>
> }
> close OUT;
> close IN;
>
> thanks a lot
> Nat
>
>
>



--
------------------------------------------------------------ -----
Shlomi Fish http://www.shlomifish.org/
What does "Zionism" mean? - http://shlom.in/def-zionism

No one knows all of Perl. Not even Larry Wall. Except Chuck Norris, who knows
all of Perl 5, Perl 6, and can answer questions about the design of Perl 7.

Please reply to list if it's a mailing list post - http://shlom.in/reply .

--
To unsubscribe, e-mail: beginners-unsubscribe@perl.org
For additional commands, e-mail: beginners-help@perl.org
http://learn.perl.org/