How could I print a #slice array elements in Perl? - arrays

I have this part of code to catch the greater value of an array immersed in a Hash. When Perl identified the biggest value the array is removed by #slice array:
if ( max(map $_->[1], #$val)){
my #slice = (#$val[1]);
my #ignored = #slice;
delete(#$val[1]);
print "$key\t #ignored\n";
warn Dumper \#slice;
}
Data:Dumper out:
$VAR1 = [
[
'3420',
'3446',
'13',
'39',
55
]
];
I want to print those information separated by tabs (\t) in one line like this list:
miRNA127 dvex589433 - 131 154
miRNA154 dvex546562 + 232 259
miRNA154 dvex573491 + 297 324
miRNA154 dvex648254 + 147 172
miRNA154 dvex648254 + 287 272
miRNA32 dvex320240 - 61 83
miRNA32 dvex623745 - 141 163
miRNA79 dvex219016 + ARRAY(0x100840378)
But in the last line always obtain this result.
How could I generate this output?:
miRNA127 dvex589433 - 131 154
miRNA154 dvex546562 + 232 259
miRNA154 dvex573491 + 297 324
miRNA154 dvex648254 + 147 172
miRNA154 dvex648254 + 287 272
miRNA32 dvex320240 - 61 83
miRNA32 dvex623745 - 141 163
miRNA79 dvex219016 + 3420 3446
Additional explication:
In this case, I want to catch the highest value in $VAR->[1] and looking if the subtraction with the minimum in $VAR->[0] is <= to 55. If not, i need to eliminate this AoA (the highest value) and fill a #ignored array with it. Next, i want to print some values of #ignored, like a list. Next, with the resultants AoA, I want to iterate the last flow...

print "$key\t $ignored[0]->[0]\t$ignored[0]->[1]";
You have an array of arrays, so each element of #ignored is an array. The notation $ignored[0] gets to the zeroth element (which is an array), and ->[0] and ->[1] retrieves the zeroth and first elements of that array.
For example:
use strict;
use warnings;
use Data::Dumper;
my #ignored;
$ignored[0] = [ '3420', '3446', '13', '39', 55 ];
my $key = 'miRNA79 dvex219016 +';
print Dumper \#ignored;
print "\n";
print "$key\t$ignored[0]->[0]\t$ignored[0]->[1]";
Output:
$VAR1 = [
[
'3420',
'3446',
'13',
'39',
55
]
];
miRNA79 dvex219016 + 3420 3446
Another option that generates the same output is to join all the values with a \t:
print join "\t", $key, #{ $ignored[0] }[ 0, 1 ];

Related

Use of uninitialized value within #spl in substitution (s///)

I am getting following error while running the script.
Use of uninitialized value in print at PreProcess.pl line 137.
Use of uninitialized value within #spl in substitution (s///) at PreProcess.pl line 137.
Is there any syntax error in the script?
(Running it in Windows - Strawberry 64 last version)
my $Dat=2;
my $a = 7;
foreach (#spl) {
if ( $_ =~ $NameInstru ) {
print $spl[$Dat] =~ s/-/\./gr, " 00:00; ",$spl[$a],"\n"; # data
$Dat += 87;
$a += 87;
}
}
inside of array i hve this type of data
"U.S. DOLLAR INDEX - ICE FUTURES U.S."
150113
2015-01-13
098662
ICUS
01
098
128104
14111
88637
505
13200
50
269
43140
34142
1862
37355
482
180
110623
126128
17480
1976
1081
-3699
8571
-120
646
50
248
1581
-8006
319
2093
31
-30
1039
1063
42
18
100.0
11.0
69.2
0.4
10.3
0.0
0.2
33.7
26.7
1.5
29.2
0.4
0.1
86.4
98.5
13.6
1.5
215
7
.
.
16
.
.
50
16
8
116
6
4
197
34
28.6
85.1
41.3
91.3
28.2
85.1
40.8
91.2
"(U.S. DOLLAR INDEX X $1000)"
"098662"
"ICUS"
"098"
"F90"
"Combined"
"U.S. DOLLAR INDEX - ICE FUTURES U.S."
150106
2015-01-06
098662
ICUS
01
098
127023
17810
80066
625
12554
0
21
41559
42148
1544
35262
452
210
109585
125065
17438
1958
19675
486
23911
49
2717
0
-73
9262
-5037
30
5873
270
95
18439
19245
1237
431
100.0
14.0
63.0
0.5
9.9
0.0
0.0
32.7
33.2
1.2
27.8
0.4
0.2
86.3
98.5
13.7
1.5
202
7
.
.
16
0
.
48
16
9
105
6
4
185
34
29.3
83.2
43.2
90.6
28.9
83.2
42.8
90.5
"(U.S. DOLLAR INDEX X $1000)"
"098662"
"ICUS"
"098"
"F90"
"Combined"
You are probably trying to load a file of data sets of a size of 87 lines each into an array, and then you get an error at the end of your data, when you try to read outside of the last array index.
You can probably solve it by iterating over the array indexes instead of the array values, e.g.
my $Dat = 2;
my $a = 7;
my $set_size = 87;
for (my $n = 0; $n + $a < #spl; $n += $set_size) {
if ( $spl[$n] =~ $NameInstru ) {
print $spl[$n + $Dat] =~ s/-/\./gr, " 00:00; ",$spl[$n + $a],"\n"; # data
}
}
While this might solve your problem, it might be better to try and find a proper way to parse your file.
If the records inside the input file are separated by a blank line, you can try to read whole records at once by changing the input record separator to "" or "\n\n". Then you can split each element in the resulting array on newline \n and get an entire record as a result. For example:
$/ = "";
my #spl;
open my $fh ...
while (<$fh>) {
push #spl, [ split "\n", $_ ];
}
...
for my $record (#spl) {
# #$record is now an 87 element array with each record in the file
}
TLP's solution of iterating over the indexes of an array, incrementing by 87 at time is great.
Here's a more complex solution, but one that doesn't require loading the entire file into memory.
my $lines_per_row = 87;
my #row;
while (<>) {
chomp;
push #row, $_;
if (#row == $lines_per_row) {
my ($instru, $dat, $a) = #row[0, 2, 7];
if ($instru =~ $NameInstru) {
print $dat =~ s/-/\./gr, " 00:00; $a\n";
}
#row = ();
}
}

Perl Multidimensional array column compare and display whole content with satisfied condition

I am facing little issue in taking array index for comparison and displaying the result. I have a tab delimited file with 9 columns and more than 100 rows. I want to compare the 8th column element of ith row with the 7th column element of i+1th row. If it is smaller than the 7th column element then print entire row else if it is greater than the 7th column element the compare the 6th element of both row and only print if the row if the 6th element is bigger.
Sample File
Recep_L_domain PF01030.22 112 sp|P00533|EGFR_HUMAN 2.50E-30 104.7 57 167 Receptor
Furin-like PF00757.18 149 sp|P00533|EGFR_HUMAN 4.10E-29 101.3 185 338 Furin-like
Recep_L_domain PF01030.22 112 sp|P00533|EGFR_HUMAN 3.60E-28 97.8 361 480 Receptor
GF_recep_IV PF14843.4 132 sp|P00533|EGFR_HUMAN 1.60E-46 157.2 505 636 Growth
Pkinase PF00069.23 264 sp|P00533|EGFR_HUMAN 2.70E-39 135 712 964 Protein
Pkinase_Tyr PF07714.15 260 sp|P00533|EGFR_HUMAN 8.40E-88 293.9 714 965 Protein
For example if we compare the last two row then 8th column element is bigger than the next row's 7th column element, then in this case it should compare the two 6th column element and print the only row which is bigger. So from this two row it should print only last row. For me the below code is only printing the values if it is smaller, but I want to ask how can I compare 6th element and print results if 8th column is bigger?
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
open(IN,"<samplecode.txt");
my #Alifrom;
my #Alito;
my #data; ## multidimensional array
while(<IN>){
chomp $_;
#next if $_=undef;
my #line = split("\t", $_);
##my($a, $b, $c, $d, $e, $f, $g, $h, $i) = split(/\t/,$_); // catch data and storing into multiple scalar variable
push #data, [#line];
}
for (my $i = 0; $i < #data ; $i++){
if ($data[$i][7] gt $data[$i][6]){
for (my $j = 0; $j < #{$data[$i]}; $j++){
##Alifrom = map $data[$i][$j+6], #data;
print "$data[$i][$j]\t";
}
}
#else
print "\n";
}
The description in your question is not entirely clear, but I'm taking an educated guess.
First, you should not read the whole file into an array. If your file really only has 100 rows, it's not a problem, but if there are more rows this will consume a lot of memory.
You say you want to compare values in every row i to values in row i+1, so essentially in every row you want to look at values in the next row. That means you need to keep a maximum of two rows in memory at one time. Since that's linear, you can just read the first row, then read the second row, compare, and when you're done make the second row the new first row.
In your loop, you always read the second row, and keep around the first row from when you read it as the second row in the iteration before.
For that, it makes sense to turn the reading and splitting into a function. You can pass it a file handle. In my example above, I've used DATA with the __DATA__ section, but you can just open my $fh, '<', 'samplecode.txt' and pass $fh around.
Because you want to print the whole row in some cases, you should not just chomp and split it in a destructive manner, but rather keep around the actual full row including the line break. We therefore make the function to read and split return two values: the full row as a scalar string, and an array reference of the cleaned up columns.
If there are no more lines to read, we return an implicit undef, which will make the while loop stop. Therefore you can never process the last row of the file.
When comparing, note that list indexes in Perl always start on zero, so column 7 is index [6].
Here's an example implementation.
use strict;
use warnings;
# this function reads a line from the filehandle that's passed in and returns
# the row as a string and an array ref of all columns, or undef if there are
# no more lines to read
sub read_and_split {
my $fh = shift;
# read one line and return undef if there is no more data
my $row = <$fh>;
return unless defined $row;
# split into columns
my #cols = split /\s+/, $row; # Stack Overflow does not like tabs, use \t
# only chomp after splitting so we retain the original line for printing
chomp $cols[-1];
# return both things
return $row, \#cols;
}
# read the first line
my ( $row_i, $cols_i ) = read_and_split( \*DATA );
# read subsequent lines
while ( my ( $row_i_plus_one, $cols_i_plus_one ) = read_and_split( \*DATA ) ) {
# 7th col of i is smaller than 6th col of i+1
if ( $cols_i->[7] < $cols_i_plus_one->[6] ) {
print $row_i;
}
else {
# compare the 6th element of both row and only print
# if the row if the 6th element is bigger
if ( $cols_i->[5] > $cols_i_plus_one->[5] ) {
print $row_i;
}
}
# turn the current i+1 into i for the next iteration
$row_i = $row_i_plus_one;
$cols_i = $cols_i_plus_one;
}
__DATA__
Recep_L_domain PF01030.22 112 sp|P00533|EGFR_HUMAN 2.50E-30 104.7 57 167 Receptor
Furin-like PF00757.18 149 sp|P00533|EGFR_HUMAN 4.10E-29 101.3 185 338 Furin-like
Recep_L_domain PF01030.22 112 sp|P00533|EGFR_HUMAN 3.60E-28 97.8 361 480 Receptor
GF_recep_IV PF14843.4 132 sp|P00533|EGFR_HUMAN 1.60E-46 157.2 505 636 Growth
Pkinase PF00069.23 264 sp|P00533|EGFR_HUMAN 2.70E-39 135 712 964 Protein
Pkinase_Tyr PF07714.15 260 sp|P00533|EGFR_HUMAN 8.40E-88 293.9 714 965 Protein
It outputs these lines:
Recep_L_domain PF01030.22 112 sp|P00533|EGFR_HUMAN 2.50E-30 104.7 57 167 Receptor
Furin-like PF00757.18 149 sp|P00533|EGFR_HUMAN 4.10E-29 101.3 185 338 Furin-like
Recep_L_domain PF01030.22 112 sp|P00533|EGFR_HUMAN 3.60E-28 97.8 361 480 Receptor
GF_recep_IV PF14843.4 132 sp|P00533|EGFR_HUMAN 1.60E-46 157.2 505 636 Growth
Note that the part about comparing columns six was not very clear in your question. I assumed we compare both columns six and print the one for row i if it's a match. If we were to print row i+1 we might end up printing that line twice.

add each column to array, not just whole line - PERL

I am writing a perl script and currently working on a subroutine to sum all values of an array. Currently, my code only reads in each line and stores the entire line into each array element. I need each individual number stored in it's own element.
Here's a sample of my data:
50 71 55 93 115
45 76 49 88 102
59 78 53 96 145
33 65 39 82 100
54 77 56 98 158
Here's my code:
my #array;
#bring in each line and store into array called 'array'
open(my $fh, "<", "score")
or die "Failed to open file: $!\n";
while(<$fh>) {
chomp;
push #array, $_;
}
close $fh;
When I call my subroutine to sum the values of the array, my result is 241. That is the sum of each of the first numbers in each line.
Any help or suggestions?
So, you want to add all values inside an array. Easy, But In your code, you are adding strings of values instead of value itself.
With push #array, $_; you are creating an array of lines in the file score.
Try:
print Dumper(\#array);
You will see output like this:
$VAR1 = [
'50 71 55 93 115',
'45 76 49 88 102',
'59 78 53 96 145',
'33 65 39 82 100',
'54 77 56 98 158'
];
So when you are adding the values, it adds all elements of array:
'50 71 55 93 115' + '59 78 53 96 145' + '33 65 39 82 100' ......and so on
The moment you put + with string it is treated as numeric and by default, perl adds first character in the string to the first character in the other string. If the first character is not a number, It is treated as 0.
You should check perlop for more info.
The solution for this problem is to separate the numbers from every line, treat each of them individually and store them inside the array. This can be done simply using:
push #array, split;
Now when you try:
print Dumper(\#array);
It will be like this:
$VAR1 = [
'50',
'71',
'55',
'93',
'115',
'45',
'76',
'49',
'88',
'102',
'59',
'78',
'53',
'96',
'145',
'33',
'65',
'39',
'82',
'100',
'54',
'77',
'56',
'98',
'158'
];
After this just call your subroutine using:
my $total_sum = sum(#array);
print $total_sum,"\n";
and define your subroutine as:
sub sum {
my #nums = #_;
my $total_sum = 0;
$total_sum += $_ foreach(#nums);
return $total_sum;
}
The output will be 1937 as expected.

how to print a certain amount of results on a single line

I want to print up to 10 results per line and then after 10 force a new line. How would I do this?
This is the code:
my #email;
my #gender;
my #state;
while ( <> ) {
chomp;
my #fields = split /,/;
push #gender, $fields[5];
push #email, $fields[3];
push #state, $fields[4];
}
#records
print "There are $_ records in this file\n" for scalar (#email-1);
print "\n";
#gender
my %count;
$count{$_}++ for #gender;
while( my ($gender => $count) = each %count) {
delete $count{gender};}
print "Male/Female distribution:\n";
print join(' ',%count), "\n";
print "\n";
#email
#states
my %scount;
$scount{$_}++ for #state;
while( my ($state => $scount) = each %scount){
delete $scount{state};}
print join(' ',%scount), "\n";
and its result:
8 NC 292 OK 163 NY 901 VA 477 PA 195 NE 62 OH 711 WV 37 NM 10 MO 7 NH 77 MA 689 MN 431 TX 920 ME 81 NJ 673 RI 91 AL 230 KS 22 ND 31 FL 461 CT 305 CA 1262 IA 139 DE 33 CO 118 MI 378 IN 211 AR 163 IL 811 KY 11
So for example I would want a new line after NM 10.
change print join(' ',%scount), "\n"; to:
my $n;
print map {$n++; $n % 10 ? "$_ $scount{$_} ":"$_ $scount{$_}\n"} keys %scount;
Possibly a bit more readable:
my #results = %count;
while (#results) {
print(join(" ", splice(#results, 10)), "\n");
}

Getting exact match in a has but with a twist

I have something I cannot get my head around
Let's say I have a phone list used for receiving and dialing out stored like below. The from and to location is specified as well.
Country1 Country2 number1 number2
USA_Chicago USA_LA 12 14
AUS_Sydney USA_Chicago 19 15
AUS_Sydney USA_Chicago 22 21
CHI_Hong-Kong RSA_Joburg 72 23
USA_LA USA_Chigaco 93 27
Now all I want to do is to remove all the duplicates and give only what is relevant to the countries as keys and each number that is assigned to it in a pair, but the pair needs to be bi-directional.
In other words I need to get results back and then print them like this.
USA_Chicago-USA_LA 27 93 12 14
Aus_Sydney-USA_Chicago 19 15 22 21
CHI_Hong-kong-RSA_Joburg 72 23
I have tried many methods including a normal hash table and the results seem fine, but it does not do the bi-direction, so I will get this instead.
USA_Chicago-USA_LA 12 14
Aus_Sydney-USA_Chicago 19 15 22 21
CHI_Hong-kong-RSA_Joburg 72 23
USA_LA-USA_Chicago 93 27
So the duplicate removal works in one way, but because there is another direction, it will not remove the duplicate "USA_LA-USA_Chicago" which already exists as "USA_Chicago-USA_LA" and will store the same numbers under a swopped name.
The hash table I tried last is something like this. (not exactly as I trashed the lot and had to rewrite it for this post)
#input= ("USA_Chicago USA_LA 12 14" ,
"AUS_Sydney USA_Chicago 19 15" ,
"AUS_Sydney USA_Chicago 22 21" ,
"CHI_Hong-Kong RSA_Joburg 72 23" '
"USA_LA USA_Chigaco 93 27");
my %hash;
for my $line (#input) {
my ($c1, $c2, $n1, $n2) = split / [\s\|]+ /x, $line6;
my $arr = $hash{$c1} ||= [];
push #$arr, "$n1 $n2";
}
for my $c1 (sort keys %hash) {
my $arr = $hash{$c1};
my $vals = join " : ", #$arr;
print "$c1 $vals\n";
}
So all if A-B exists and so does B-A, use only one but assign the values from the key being removed, to the remaining key. I basically need to do is get rid of any duplicate key in any direction, but assign the values for to the remaining key. So A-B and B-A would be considered a duplicate, but A-C and B-C are not. -_-
Simply normalise the destinations. I chose to sort them.
use strictures;
use Hash::MultiKey qw();
my #input = (
'USA_Chicago USA_LA 12 14',
'AUS_Sydney USA_Chicago 19 15',
'AUS_Sydney USA_Chicago 22 21',
'CHI_Hong-Kong RSA_Joburg 72 23',
'USA_LA USA_Chicago 93 27'
);
tie my %hash, 'Hash::MultiKey';
for my $line (#input) {
my ($c1, $c2, $n1, $n2) = split / [\s\|]+ /x, $line;
my %map = ($c1 => $n1, $c2 => $n2);
push #{ $hash{[sort keys %map]} }, #map{sort keys %map};
}
__END__
(
['CHI_Hong-Kong', 'RSA_Joburg'] => [72, 23],
['AUS_Sydney', 'USA_Chicago'] => [19, 15, 22, 21],
['USA_Chicago', 'USA_LA'] => [12, 14, 27, 93],
)
Perl is great for creating complex data structures but learning to use them effectively takes practices.
Try:
#!/usr/bin/env perl
use strict;
use warnings;
# --------------------------------------
use charnames qw( :full :short );
use English qw( -no_match_vars ); # Avoids regex performance penalty
use Data::Dumper;
# Make Data::Dumper pretty
$Data::Dumper::Sortkeys = 1;
$Data::Dumper::Indent = 1;
# Set maximum depth for Data::Dumper, zero means unlimited
local $Data::Dumper::Maxdepth = 0;
# conditional compile DEBUGging statements
# See http://lookatperl.blogspot.ca/2013/07/a-look-at-conditional-compiling-of.html
use constant DEBUG => $ENV{DEBUG};
# --------------------------------------
# skip the column headers
<DATA>;
my %bidirectional = ();
while( my $line = <DATA> ){
chomp $line;
my ( $country1, $country2, $number1, $number2 ) = split ' ', $line;
push #{ $bidirectional{ $country1 }{ $country2 } }, [ $number1, $number2 ];
push #{ $bidirectional{ $country2 }{ $country1 } }, [ $number1, $number2 ];
}
print Dumper \%bidirectional;
__DATA__
Country1 Country2 number1 number2
USA_Chicago USA_LA 12 14
AUS_Sydney USA_Chicago 19 15
AUS_Sydney USA_Chicago 22 21
CHI_Hong-Kong RSA_Joburg 72 23
USA_LA USA_Chicago 93 27

Resources