regex - Foreach loop only acting on a portion of the first element in an array -
i have 5 fasta files in directory, can put array. when attempt open files in succession via foreach loop, perform regex on each file, first file in directory seems open processing. furthermore, when try print entire sequence in first file (via diagnostic print statement not shown), first half of sequence ignored. latter portion of sequence printed. if has insights on how overcome this, grateful. here code looks far.
#!/usr/bin/perl use warnings; use strict; use diagnostics; $dir = ("/users/roblogan/documents/fakefastafilesagain"); @trimmedsequences; @arrayoffiles = glob "$dir/*"; #print join("\n", @arrayoffiles), "\n"; # diagnostic test print statement foreach $file (@arrayoffiles){ open (my $sequence, '<', $file) or die $!; # open each file in array while (my $line = <$sequence>) { $line =~ s/\r//g; # rid of new line breaks if ($line =~ m/(ctccca)[tagc]+(tcagga)/) { # search file contents push(@trimmedsequences, $line); # push match array close $file; } } } print join("\n", @trimmedsequences), "\n";
testing code (or similar it) works fine when removing close statement. using close breaks loop finds match. leaving 1 result per file.
also note, don't need call close @ all. file closed when variable $sequence loses scope.
chomp
should used rid of newlines
here test code. note few edits.
#!/usr/bin/perl use strict; use warnings; $files = ("."); @files = grep { $_ =~ /\.pl/} glob "$files/*"; #added filter out directies in test directory, can ignored @lines; #use in perl not foreach $file (@files){ open $fh, '<', $file or die $!; while(my $line = <$fh>){ chomp($line); #use chomp remove newlines if($line =~ /use/){ push @lines, $line; #no need call close @ all, filehandle closed when loses scope } } } print join("\n", @lines) . "\n";
does expected in test directory , prints use statements perl files have in directory.
Comments
Post a Comment