Convert string into array perl - arrays

I have a script which takes headers of a multi-fasta file and pushes them into an array. Then I want to loop through this array to find a specific pattern and perform some commands.
open(FH, '<', $ref_seq) or die $!;
while(<FH>){
$line = $_;
chomp $line;
if(m/^>([^\s]+)/){
$ref_header = $1;
print "$ref_header\n";
chomp $header;
if($1 eq $header){
$ref_header = $header;
#print "header is $ref_header\n";
}
}
}
This code prints headers like
chr1
chr2
chr3
How can I push these headers into an array?
I tried following code, but it splits individual letters, instead of $header_array[0] being chr1
#header_array = split(/\n*/, $ref_header);
print ("Here's the first element $header_array[0]");
Any help will be appreciated.

Shorten the code as shown below, removing some extra statements, and use push. You can combine push and the pattern match:
#!/usr/bin/env perl
use strict;
use warnings;
use Carp;
my $in_file = shift;
my #headers;
open my $in_fh, '<', $in_file or croak "cannot open $in_file: $!";
while ( <$in_fh> ) {
push #headers, />(\S+)/;
}
close $in_fh or croak "cannot close $in_file: $!";
print "#headers";
# Now, loop through headers and select the ones you need, for example:
for my $header ( #headers ) {
if ( $header =~ /foo/ ) {
# do something
}
}
A few suggestion on fixing your original code are below:
# Always use strict and use warnings.
# Remove extra parens and make the error message more informative:
open(FH, '<', $ref_seq) or die $!;
while(<FH>){
$line = $_;
chomp $line;
# [^\s] is simply \S:
if(m/^>([^\s]+)/){
$ref_header = $1;
print "$ref_header\n";
# where is $header coming from?
chomp $header;
# if the condition is satisfied, this assignment does not make sense:
# $ref_header is already the same as $header:
if($1 eq $header){
$ref_header = $header;
#print "header is $ref_header\n";
}
}
}

You can use push:
push #header_array, $ref_header;

Related

How to count the number of keys that exist in a hash?

I am working with an input file that contains tab delimitated sequences. Groups of sequences are separated by line breaks. The file looks like:
TAGC TAGC TAGC HELP
TAGC TAGC TAGC
TAGC HELP
TAGC
Here is the code I have:
use strict;
use warnings;
open(INFILE, "<", "/path/to/infile.txt") or die $!;
my %hash = (
TAGC => 'THIS_EXISTS',
GCTA => 'THIS_DOESNT_EXIST',
);
while (my $line = <INFILE>){
chomp $line;
my $hash;
my #elements = split "\t", $line;
open my $out, '>', "/path/to/outfile.txt" or die $!;
foreach my $sequence(#elements){
if (exists $hash{$sequence}){
print $out ">$sequence\n$hash{$sequence}\n";
}
else
}
$count++;
print "Doesn't exist ", $count, "\n";
}
}
}
How can I tell how many sequences exist before I print? I need to put that information into the name of the output file.
Ideally, I would have a variable that I could include in the name of the file. Unfortunately, I can't just take the scalar of #elements because there are some sequences that won't get printed out. When I try to push the keys that exist into an array and then print the scalar of that array, I still don't get the results I need. Here is what I tried (all variables that need to be global are):
open my $out, '>', "/path/to/file.$number.txt" or die $!;
foreach my $sequence(#elements){
if (exists $hash{$sequence}){
push(#Array, $hash{$sequence}, "\n");
my $number = #Array;
print $out ">$sequence\n$hash{$sequence}\n";
#....
Thanks for the help. Really appreciate it.
my $sequences = grep exists $hash{$_}, #elements;
open my $out, '>', "/path/to/outfile_containing_$sequences.txt" or die $!;
In list context, grep filters a list by a criterion; in scalar context, it returns a count of elements that met the criterion.
The easiest way would be to keep track of how many keys you are printing in a variable and once your loop finish, just rename the file with the number you calculated. Perl comes with a built-in function to do this. The code would be something like this:
use strict;
use warnings;
open(INFILE, "<", "/path/to/infile.txt") or die $!;
my %hash = (
TAGC => 'THIS_EXISTS',
GCTA => 'THIS_DOESNT_EXIST',
);
my $ammt;
while (my $line = <INFILE>){
chomp $line;
my $hash;
my #elements = split "\t", $line;
open my $out, '>', "/path/to/outfile.txt" or die $!;
foreach my $sequence(#elements){
if (exists $hash{$sequence}){
print $out ">$sequence\n$hash{$sequence}\n";
$ammt++;
}
else
}
print "Doesn't exist ", $count, "\n";
}
}
}
rename "/path/to/outfile.txt", "/path/to/outfile${ammt}.txt" or die $!;
I removed the $count variable, since it's not declared in your code (strict would complain about that). Here's the official doc for rename. Since it returns True or False, you can check that it was successful or not.
By the way, be aware that:
push(#Array, $hash{$sequence}, "\n");
is storing two items ($hash{$sequence} and \n), so that count would be twice as it should be.

To remove duplicate elements from an array in Perl

I have a data set
10-101570715-101609901-hsa-mir-3158-1 10-101600739-101609661-ENSG00000166171 10-101588288-101609668-ENSG00000166171 10-101588325-101609447-ENSG00000166171 10-101594702-101609439-ENSG00000166171 10-101570560-101596651-ENSG00000166171
10-103389007-103396515-hsa-mir-1307 10-103389041-103396023-ENSG00000173915 10-103389050-103396074-ENSG00000173915 10-103389050-103396441-ENSG00000173915 10-103389050-103396466-ENSG00000173915 10-103389050-103396466-ENSG00000173915
Except for the first element in each line, I have multiple values, which are redundant and I want to remove the redundant values. I have written a code but I don't feel its working fine.
open (fh, "file1");
while ($line=<fh>)
{
chomp ($line);
#array=$line;
my #unique = ();
my %Seen = ();
foreach my $elem ( #array )
{
next if $Seen{ $elem }++;
push #unique, $elem;
}
print #unique;
}
a hash is for duplicate detection :
my %seen;
my #removeduplicate = grep { !$seen{$_}++ } #array;
For me below code is working fine :
use strict;
use warnings;
my %seen;
open my $fh, "<", 'file.txt' or die "couldn't open : $!";
while ( my $line = <$fh>)
{
chomp $line;
my #array = split (' ', $line);
my #removeduplicate = grep { !$seen{$_}++ } #array;
print "#removeduplicate\n";
}

Perl Hashes of Arrays and Some issues

I currently have a csv file that looks like this:
a,b
a,d
a,f
c,h
c,d
So I saved these into a hash such that the key "a" is an array with "b,d,f" and the key "c" is an array with "h,d"... this is what I used for that:
while(<$fh>)
{
chomp;
my #row = split /,/;
my $cat = shift #row;
$category = $cat if (!($cat eq $category)) ;
push #{$hash{$category}}, #row;
}
close($fh);
Not sure about the efficiency but it seems to work when I do a Data Dump...
Now, the issue I'm having is this; I want to create a new file for each key, and in each of those files I want to print every element in the key, as such:
file "a" would look like this:
b
d
f
<end of file>
Any ideas? Everything I've tried isn't working, I'm not too familiar / experienced with hashes...
Thanks in advance :)
The output process is very simple using the each iterator, which provides the key and value pair for the next hash element in a single call
use strict;
use warnings;
use autodie;
open my $fh, '<', 'myfile.csv';
my %data;
while (<$fh>) {
chomp;
my ($cat, $val) = split /,/;
push #{ $data{$cat} }, $val;
}
while (my ($cat, $values) = each %data) {
open my $out_fh, '>', $cat;
print $out_fh "$_\n" for #$values;
}
#!/usr/bin/perl
use strict;
use warnings;
my %foos_by_cat;
{
open(my $fh_in, '<', ...) or die $!;
while (<$fh_in>) {
chomp;
my ($cat, $foo) = split /,/;
push #{ $foos_by_cat{$cat} }, $foo;
}
}
for my $cat (keys %foos_by_cat) {
open(my $fh_out, '>', $cat) or die $!;
for my $foo (#{ $foos_by_cat{$cat} }) {
print($fh_out "$foo\n");
}
}
I wrote the inner loop as I did to show the symmetry between reading and writing, but it can also be written as follows:
print($fh_out "$_\n") for #{ $foos_by_cat{$cat} };

match a list of identifiers to another list using perl

I am stuck on how to loop a list over another list. Perhaps I am not searching for the right words but I am stuck and would appreciate any help on my code.
I went over this thread but am still getting errors running my script. How do I search a Perl array for a matching string?
the database file
chr1 1692239 1692249 AH_GARP2_comp198_c0_seq1
chr1 2233934 2233944 CS_GARP2_comp323_c0_seq1
chr1 5993434 5993444 CS_GARP2_comp635_c0_seq1
chr1 6198157 6198167 CS_GARP2_comp115_c0_seq1
chr1 6465781 6465791 JB_GARP2_comp560_c0_seq1
chr1 7827923 7827933 JB_GARP2_comp855_c0_seq1
chr1 7920939 7920949 AA_GARP2_comp614_c0_seq1
chr1 7964000 7964010 CS_GARP2_comp717_c0_seq1
chr1 9314857 9314867 AH_GARP2_comp237_c0_seq1
chr1 9654532 9654542 AH_GARP2_comp632_c0_seq1
the query file
name1 CS_GARP2_comp635_c0_seq1
name2 JB_GARP2_comp855_c0_seq1
name3 AH_GARP2_comp198_c0_seq1
name4 AH_GARP2_comp237_c0_seq1
My code
#!/usr/bin/perl5.16.2
use 5.16.2;
use lib '/users/ec1/perl5/lib/perl5/';
use warnings;
use strict;
my $filename = shift; ## database
my $filename2= shift; ## list of ids
open (DB, '<', $filename ) || die "Unable to open: $!";
open (I , '<', $filename2) || die "Unable to open: $!";
my #DB;
while (<DB>) {
chomp;
my #DB = split /\t/, $_; ## define as list
#print "#DB[0,1,2,3]\n";
}
while (my $line = <I>) {
chomp $line;
my ($name, $id) = split /\t/, $line;
if ($DB[3] =~ /$id/) {print "$DB[0]\t$DB[1]\t$DB[2]\t$DB[3]\n";
} else {print "na\n"}
}
Put DB into hash (%DB) to ease searches.
use strict; use warnings;
my $filename = shift; ## database
my $filename2= shift; ## list of ids
my %DB;
open (DB, '<', $filename ) || die "Unable to open: $!";
while (<DB>) {
chomp;
my #row = split( /[ \t]+/, $_); ## define as list
die "expected four items in db file - line $.\n" unless #row == 4; # expect four elements in a row
die "duplicate id in db file - line $." if exists $DB{$row[3]};
$DB{$row[3]} = \#row;
}
close DB;
open (I , '<', $filename2) || die "Unable to open: $!";
while (<I>) {
chomp;
my ($name, $id) = split /[ \t]+/, $_;
if(exists ($DB{$id})) {
my #row = #{$DB{$id}};
print join("\t", #row), "\n";
} else {
print "na\n"
}
}
close(I);
P.S. I have changed split pattern to ease tests of copy&paste data file content
The problem with your approach is that the my #DB inside while loop creates a lexical scope so it will always contain the last line's contents and that content will not be available outside the loop.
You should read the id file in to a hash map and check if the line for db file exists as a key in hash.
#!/usr/bin/perl
use warnings;
use strict;
use autodie;
my ($dbfile, $idfile) = #ARGV;
open my $id_fh, '<', $idfile;
open my $db_fh, '<', $dbfile;
my %ids;
while (<$id_fh>) {
++$ids{$_} for (split /\s+/)[1]; # split and put column2 as key in %ids.
}
while (<$db_fh>) {
my $fld = (split /\s+/)[3]; # split and assign column4 to $fld
print "na\n" and next unless $ids{$fld}; # print "na" if fld is not in hash and move to next line
print "$_"; # print the line if column4 exits.
}

problem with the code in perl

My problem is that I am not able to figure out that why my code is taking each of the line from the file as one element of an array instead of taking the whole record starting from AD to SS as one element of the array. As you can see that my file is starting from AD and ending at SS which is same for all the followed lines in the data. But I want to make the array having elements starting from AD to SS which will be having all the lines in between AD to SS that is BC....,EG...., FA.....etc.not each line as an element. I tried my way and get the same file as such.Could anyone check my code. Thanks in advance.
AD uuu23
BC jjj
EG iii
FA vvv
SS
AD hhh25
BC kkk
EG ppp
FA aaa
SS
AD ttt26
BC xxx
FA rrr
SS
#!/usr/bin/env perl
use strict;
use warnings;
my $ifh;
my $line = '';
my #data;
my $ifn = "fac.txt";
open ($ifh, "<$ifn") || die "can't open $ifn";
my $a = "AD ";
my $b = "SS ";
my $_ = " ";
while ($line = <$ifh>)
{
chomp
if ($line =~ m/$a/g); {
$line = $_;
push #data, $line;
while ($line = <$ifh>)
{
$line .= $_;
push #data, $line;
last if
($line =~ m/$b/g);
}
}
push #data, $line; }
print #data;
If I understand correctly your problem, the fact is that the way you are reading the file:
while ($line = <$ifh>)
is inherently a line-by-line approach. It uses the content of the "line termination variable" ($/) to understand where to split lines. One easy way to change this behavior is un-defining the $/:
my $oldTerminator = $/;
undef $/;
....... <your processing here>
$/ = $oldTerminator;
so, your file would be just one line, but I am not sure what would happen of your code.
Another approach is the following (keeping in mind what I said about the fact that you are reading the file line-by-line): instead of doing
`push #data, $line;`
at each iteration of your loop, just accumulate the lines you read in a variable
$line .= $_;
(like you already do), and do the push only at the end, just once. Actually, this second approach will be more easily applicable to your code (you only have to remove the two push statements you have and put one outside of the loop).
I believe part of your problem is here
chomp
if ($line =~ m/$a/g);
it should be
chomp;
if ($line =~ m/$a/g)
otherwise the if statement is always executed. Please update your question if this has helped you advance
Here's a way to accomplish reading the records into an array, with newlines removed:
Code:
use strict;
use warnings;
use autodie;
my #data;
my $record;
my $file = "fac.txt";
open my $fh, '<', $file;
while (<$fh>) {
chomp;
if (/^AD /) { # new record starts
$record = $_;
while (<$fh>) {
chomp;
$record .= $_;
last if /^SS\s*/;
}
push #data, $record;
} else { die "Data outside record: $_" }
}
use Data::Dumper;
print Dumper \#data;
Output:
$VAR1 = [
'AD uuu23BC jjjEG iiiFA vvvSS',
'AD hhh25BC kkkEG pppFA aaaSS',
'AD ttt26BC xxxFA rrrSS'
];
This is another version, using the input record separator $/:
use strict;
use warnings;
use autodie;
my $file = "fac.txt";
open my $fh, '<', $file;
my #data;
$/ = "\nSS";
while (<$fh>) {
s/\n//g;
push #data, $_;
}
use Data::Dumper;
print Dumper \#data;
Produces the same output with this data. It does not care about the record start characters, only the end, which is SS at the beginning of a line.

Resources