Is there any way that number of elements iterated in an for loop can be traced in perl:
Like using special variables:
#arrayElements = (2,3,4,5,6,7,67);
foreach (#arrayElements) {
# Do something
# Want to know how may elements been iterated after
# some n number of elements processed without using another variable.
}
Either just count as you go:
my $processed = 0;
foreach my $element (#array_elements) {
...
++$processed;
}
or iterate over the indexes instead:
foreach my $index (0..$#array_elements) {
my $element = $array_elements[$index];
...
}
In perl5 v12 and later, you can use the each iterator:
while(my($index, $element) = each #array_elements) {
...;
}
However, the more portable solution is to iterate over the indices, and manually access the element, as shown by ysth.
In any case, the number of elements that were visited (including the current element) is $index + 1.
You may get the number of elements in an array as
my $num = #arrayElements;
print $num;
OR
my $num = scalar (#arrayElements);
print $num;
OR
my $num = $#arrayElements + 1;
print $num;
And for finding number of elements iterated, we can use the below code :
my $count = 0; #initially set the count to 0
foreach my $index(#arrayElements)
{
$count++;
}
print $count;
Related
I have a method where I give two arguments: one array and one string. The problem is when I initialise two different variables, one for the array and one for the string, I get the first element of the array in the first variable and the second element in the second variable. My question is how can I get the whole array in a variable and the string in a different variable?
Analyze.pm
sub analyze {
my $self = shift;
my ($content, $stringToSearch) = #_;
# my ($stringToSearch) = #_;
print "$stringToSearch";
if (!defined($stringToSearch) or length($stringToSearch) == 0) { die 'stringToSearch is not defined yet! ' }
foreach my $element ($content) {
#print "$element";
my $loc = index($element, $stringToSearch);
# print "$loc\n";
given ($stringToSearch) {
when ($stringToSearch eq "Hi") {
if ($loc != 0) {
print "Searched word is Hi \n";
} else {
print "No word found like this one! "
}
}
#when ($stringToSearch == 'ORIENTED_EDGE') {
# print 'Searched word is ORIENTED_EDGE';
#} # Printed out because i dont need it now!
}
break; # For testing
}
}
example.pm
my #fileContent = ('Hi', 'There', 'Its', 'Me')
my $analyzer = Analyze->new();
$analyzer->analyze(#fileContent, 'Hi');
When I change $content to #content it puts all the values of the array and the string in #content
I hope someone is able to help me. I'm a beginner in Perl. Thanks in advance
You can't pass arrays to subs (or methods), only a list of scalars. As such,
$analyzer->analyze(#lines, 'Hi');
is the same as as
$analyzer->analyze($lines[0], $lines[1], ..., 'Hi');
It means that the following won't work well:
my (#strings, $target) = #_;
Perl doesn't know how many items belonged to the original array, so it places them all in #strings, leaving $target undefined.
Solutions
You can do what you want as follows:
sub analyze {
my $self = shift;
my $target = pop;
my #strings = #_
for my $string (#strings) {
...
}
}
$analyzer->analyze(#lines, 'Hi')
Or without the needless copy:
sub analyze {
my $self = shift;
my $target = pop;
for my $string (#_) {
...
}
}
$analyzer->analyze(#lines, 'Hi')
Passing the target first can be easier.
sub analyze {
my ($self, $target, #strings) = #_;
for my $string (#strings) {
...
}
}
$analyzer->analyze('Hi', #lines)
Or without the needless copy:
sub analyze {
my $self = shift;
my $target = shift;
for my $string (#_) {
...
}
}
$analyzer->analyze('Hi', #lines)
You could also pass a reference to the array (in any order you like) since a reference is a scalar.
sub analyze {
my ($self, $target, $strings) = #_;
for my $string (#$strings) {
...
}
}
$analyzer->analyze('Hi', \#lines)
I would go with the second to last. It follows the same general pattern as the well-known grep.
my #matches = grep { condition($_) } #strings;
I'd just like to add a slightly different method of passing an array to a subroutine.
# Begin main program
my #arr=(1,2,3);
my $i=0;
mysub(\#arr,$i); # Pass the reference to the array
exit; # Exit main program
##########
sub mysub
{my($aref,$i)=#_; # We are receiving an array ref.
my #arr=#$aref; # Now we are back to a regular array.
print "$arr[0]\n$arr[1]\n$arr[2]\n";
return;
}
I am having an error saying that prototype not terminated at filename.txt line number 113 where as line number 113 belongs to a different program which is running successfully.
sub howmany(
my #H = #_;
my $m = 0;
foreach $x (#H) {
if ( $x > 5 ) {
$m +=1;
}
else {
$m +=0;
}
}
print "Number of elements greater than 5 is equal to: $m \n";
}
howmany(1,6,9);
The sub keyword should be followed by { } not ( ) (if you define a simple function), that's why the error
prototype not terminated
After this, always start with : use strict; use warnings;
Put this and debug your script, there's more errors.
Last but not least, indent your code properly, using an editor with syntax highlighting, you will save many time debugging
The error is due to parenthesis.
Never do $m += 0; As you actually load processor for nothing. Of course it's not gonna be visible on such a small function, but...
sub howmany {
my $m = 0;
foreach (#_) {
$m++ if ($_ > 5);
}
print "Number of elements greater than 5 is equal to: $m \n";
}
howmany(1,6,9);
I need to test a file with each line having the same number of columns and each entry is some value and I want to only select those lines with every values greater than, say 0.5.
I know I can loop through the array in each line by doing something like this:
open (IN, shift #ARGV);
while (<IN>){
chomp;
my $count = 0;
my #array = split/\t/;
foreach (#array){
if ($_ > 0.5) {
$count ++;
}
}
if ($count == scalar #array){
print $_,"\n";
}
}
close IN;
This is kinda long and I'm wondering if there is a better way to do it?
Thanks.
Use all from List::Util - it checks if passed code block (often with condition) returns true for all elements of list.
use List::Util qw(all);
if (all { $_ > 0.5 } #array) {
print "Pass!"
}
It will even short-circuit for you, terminating as soon as it finds first false value, producing most speed-effective result.
my #array = 10 .. 20;
# compare size of array with list size of grep
if (#array == grep { $_ > 0.5 } #array) {
print "All are greater than 0.5\n";
}
I have a Perl-Script, which executes a recursive function. Within it compares two elements of a 2dimensional Array:
I call the routine with a 2D-Array "#data" and "0" as a starting value. First I load the parameters into a separate 2D-Array "#test"
Then I want to see, if the array contains only one Element --> Compare if the last Element == the first. And this is where the Error occurs: Modification of non creatable array value attempted, subscript -1.
You tried to make an array value spring into existence, and the subscript was probably negative, even counting from end of the array backwards.
This didn't help me much...I'm pretty sure it has to do with the if-clause "$counter-1". But I don't know what, hope you guys can help me!
routine(#data,0);
sub routine {
my #test #(2d-Array)
my $counter = $_[-1]
for(my $c=0; $_[$c] ne $_[-1]; $c++){
for (my $j=0; $j<13;$j++){ #Each element has 13 other elements
$test[$c][$j] = $_[$c][$j];
}
}
if ($test[$counter-1][1] eq $test[-1][1]{
$puffertime = $test[$counter][4];
}
else{
for (my $l=0; $l<=$counter;$l++){
$puffertime+= $test[$l][4]
}
}
}
#
#
#
if ($puffertime <90){
if($test[$counter][8]==0){
$counter++;
routine(#test,$counter);
}
else{ return (print"false");}
}
else{return (print "true");}
Weird thing is that I tried it out this morning, and it worked. After a short time of running he again came up with this error message. Might be that I didn't catch up a error constellation, which could happen by the dynamic database-entries.
Your routine() function would be easier to read if it starts off like this:
sub routine {
my #data = #_;
my $counter = pop(#data);
my #test;
for(my $c=0; $c <= $#data; $c++){
for (my $j=0; $j<13;$j++){ #Each element has 13 other elements
$test[$c][$j] = $data[$c][$j];
}
}
You can check to see if #data only has one element by doing scalar(#data) == 1 or $#data == 0. From your code snippet, I do not see why you need to copy the data to passed to routine() to #test. Seems superfluous. You can just as well skip all this copying if you are not going to modify any of the data passed to your routine.
Your next code might look like this:
if ($#test == 0) {
$puffertime = $test[0][4];
} else {
for (my $l=0; $l <= $counter; $l++) {
$puffertime += $test[$l][4];
}
}
But if your global variable $puffertime was initialized to zero then you can replace this code with:
for (my $l=0; $l <= $counter; $l++) {
$puffertime += $test[$l][4];
}
I have a program that creates an array of hashes while parsing a FASTA file. Here is my code
use strict;
use warnings;
my $docName = "A_gen.txt";
my $alleleCount = 0;
my $flag = 1;
my $tempSequence;
my #tempHeader;
my #arrayOfHashes = ();
my $fastaDoc = open(my $FH, '<', $docName);
my #fileArray = <$FH>;
for (my $i = 0; $i <= $#fileArray; $i++) {
if ($fileArray[$i] =~ m/>/) { # creates a header for the hashes
$flag = 0;
$fileArray[$i] =~ s/>//;
$alleleCount++;
#tempHeader = split / /, $fileArray[$i];
pop(#tempHeader); # removes the pointless bp
for (my $j = 0; $j <= scalar(#tempHeader)-1; $j++) {
print $tempHeader[$j];
if ($j < scalar(#tempHeader)-1) {
print " : "};
if ($j == scalar(#tempHeader) - 1) {
print "\n";
};
}
}
# push(#arrayOfHashes, "$i");
if ($fileArray[$i++] =~ m/>/) { # goes to next line
push(#arrayOfHashes, {
id => $tempHeader[0],
hla => $tempHeader[1],
bpCount => $tempHeader[2],
sequence => $tempSequence
});
print $arrayOfHashes[0]{id};
#tempHeader = ();
$tempSequence = "";
}
$i--; # puts i back to the current line
if ($flag == 1) {
$tempSequence = $tempSequence.$fileArray[$i];
}
}
print $arrayOfHashes[0]{id};
print "\n";
print $alleleCount."\n";
print $#fileArray +1;
My problem is when the line
print $arrayOfHashes[0]{id};
is called, I get an error that says
Use of uninitialized value in print at fasta_tie.pl line 47, line 6670.
You will see in the above code I commented out a line that says
push(#arrayOfHashes, "$i");
because I wanted to make sure that the hash works. Also the data prints correctly in the
desired formatting. Which looks like this
HLA:HLA00127 : A*74:01 : 2918
try to add
print "Array length:" . scalar(#arrayOfHashes) . "\n";
before
print $arrayOfHashes[0]{id};
So you can see, if you got some content in your variable. You can also use the module Data::Dumper to see the content.
use Data::Dumper;
print Dumper(\#arrayOfHashes);
Note the '\' before the array!
Output would be something like:
$VAR1 = [
{
'sequence' => 'tempSequence',
'hla' => 'hla',
'bpCount' => 'bpCount',
'id' => 'id'
}
];
But if there's a Module for Fasta, try to use this. You don't have to reinvent the wheel each time ;)
First you do this:
$fileArray[$i] =~ s/>//;
Then later you try to match like this:
$fileArray[$i++] =~ m/>/
You step through the file array, removing the first "greater than" sign in the line on each line. And then you want to match the current line by that same character. That would be okay if you only want to push the line if it has a second "greater than", but you will never push anything into the array if you only expect 1, or there turns out to be only one.
Your comment "puts i back to the current line" shows what you were trying to do, but if you only use it once, why not use the expression $i + 1?
Also, because you're incrementing it post-fix and not using it for anything, your increment has no effect. If $i==0 before, then $fileArray[$i++] still accesses $fileArray[0], only $i==1 after the expression has been evaluated--and to no effect--until being later decremented.
If you want to peek ahead, then it is better to use the pre-fix increment:
if ($fileArray[++$i] =~ m/>/) ...