Perl Circle Array Function - arrays

I am searching for help on how to loop through an array. I have source code that takes a number for a radius of a circle and produces its circumference. This only takes one number, and I would like to get multiple circumferences.
#!/usr/bin/env perl
use warnings;
$pi = 3.141592654;
print "What's the radius? ";
chomp($radius = <STDIN>);
$circle = 2 * $pi * $radius;
if ($radius < 0 ) {
$circle = 0;
}
print "The circumference of a circle with the radius of $radius is $circle.\n";
Now I want to be able to input several numbers for multiple radii using a while loop to put them into an array. Once I enter 0 or a number less than 0 the while loop will exit and the program will continue by looping through the array of user entered numbers and calculate the circumference of each circle using those values as a radii.
I have some code that is trying to do this, but I cannot seem to get it to work.
#number = <STDIN>;
while(<>) {
print "whats the radius? ";
my($circle, $radius, $pi);
$radius = &rad(<STDIN>);
$pi = 3.141592654;
$circle = 2 * $pi * $radius;
if ($radius <= 0){
return $circle; }
}
Any direction of where to go, or a simple solution would be greatly appreciated.

To do that with an array, you need to first read until you get a zero and push. Then you can process the array using a for or foreach loop. Those two are the same, but the syntax commonly associated with foreach is more perlish.
use strict;
use warnings;
# turn on autoflush so stuff gets printed immediately
$|++;
print "Please enter a bunch of numbers, or 0 to stop. ";
my #numbers;
while ( my $n = <> ) {
chomp $n;
# stop at zero or less
last if $n <= 0;
# store the number in the array
push #numbers, $n;
}
my $pi = 3.141592654;
foreach my $radius (#numbers) {
my $circumference = 2 * $pi * $radius;
# print with format (%s gets replaced by params)
printf "The circumference of a circle with radius %s is %s\n", $radius, $circumference;
}
Here's the input/output.
Please enter a bunch of numbers, or 0 to stop. 1
2
3
0
The circumference of a circle with radius '1' is '6.283185308'
The circumference of a circle with radius '2' is '12.566370616'
The circumference of a circle with radius '3' is '18.849555924'
When running your first program, I noticed that the What's the radius? message showed up under the input prompt. That is because your output buffer only gets flushed when you have a newline \n in the output (or in some other cases, but let's ignore those). To change that behaviour, you can enable autoflush on the buffer, or simply set $| to a value larger than zero. The increment-idiom is common to do that.
You can also use the Math::Trig module to get π. It comes with Perl and has a constant that gives you pi. Since constants in Perl are just subs, you import it like any other function from a module.
use strict;
use warnings;
use Math::Trig 'pi'; # load module and import the 'pi' constant
# ...
foreach my $radius (#numbers) {
my $circumference = 2 * pi * $radius;
# print with format (%s gets replaced by params)
printf "The circumference of a circle with radius %s is %s\n", $radius, $circumference;
}

use strict;
use warnings;
use Data::Dumper;
This repeats your code in a infinite loop, exiting if the radius <= 0.
It stores all corresponding values for circle and radius in arrays:
my (#circle, #radius);
while(1){
print "What's the radius? ";
chomp($radius = <STDIN>);
$circle = 2 * $pi * $radius;
print "The circumference of a circle with the radius of $radius is $circle.\n";
last if $radius <= 0;
push #circle, $circle;
push #radius, $radius;
}
print Dumper \#circle, \#radius;

Easier than it might sound - tone of the key ways of interacting with an array is via a for (or foreach - they're the same) loop. Each iteration of the loop, a variable is set to the iterator - you can specify it (I have below) but if you don't it uses $_ by default.
#!/usr/bin/perl
use strict;
use warnings;
my $PI = 3.141592654;
print "Please enter radii, terminate with ^D\n";
my #list_of_values = <STDIN>;
chomp ( #list_of_values ); #remove linefeeds
foreach my $radius ( #list_of_values ) {
print "Circumference of radius $radius is: ", $PI * $radius * 2,"\n";
}
The other trick I use above - is reading STDIN. Perl knows the difference between reading a single value - into a scalar - or reading a sequence of values into an array.
So it'll behave differently if you:
my $value = <STDIN>; #reads one line
my #values = <STDIN>; #reads all the lines
You could also do this with:
#!/usr/bin/perl
use strict;
use warnings;
my $PI = 3.141592654;
my #list_of_values;
print "Enter radii, or \"done\" if complete\n";
while ( my $input = <STDIN> ) {
chomp($input);
last if $input eq "done";
if ( $input =~ m/^[\d\.]+$/ ) {
push( #list_of_values, $input );
}
else {
print "Input of \"$input\" is invalid, please try again\n";
}
}
foreach my $radius (#list_of_values) {
print "Circumference of radius $radius is: ", $PI * $radius * 2, "\n";
}
for and foreach do the same thing, it's a matter of style which you use.

Related

Perl Program to Count Two Character Frequencies

I am trying to find two character strings in a text file and print them and their frequencies out.
#!/usr/bin/perl
#digram finder
use strict; use warnings;
#finds digrams in a file and prints them and their frequencies out
die "Must input file\n" if (#ARGV != 1);
my ($file) = #ARGV;
my %wordcount;
open (my $in, "<$file") or die "Can't open $file\n";
while (my $words = <$in>){
chomp $words;
my $length = length($words);
for (my $i = 0; $i<$length; $i++){
my $duo = substr($words, $i; 2);
if (not exists $wordcount{$duo}){
$wordcount{$duo} = 1;
}
else {
$wordcount{$duo}++;
}
}
}
foreach my $word (sort {$wordcount{$b} cmp $wordcount{$a}} keys %wordcount){
print "$word\t$wordcount{$duo}\n";
}
close($in);
First I set the text file to a string $words.
Then, I run a for loop and create a substring $duo at each position along $words
If $duo doesn't exist within the hash %wordcount, then the program creates the key $duo
If $duo does exist, then the count for that key goes up by 1
Then the program prints out the digrams and their frequencies, in order of decreasing frequency
When I try to run the code, I get the error message that I forgot to declare $word on line 17 but I do not even have the string $word. I am not sure where this error message is coming from. Can someone help me find where the error is coming from?
Thank you
My best guess is that you actually have $word instead of $words; a typo. If the compilation found the symbol $word in the text then it's probably there.
However, I'd also like to comment on the code. A cleaned up version
while (my $words = <$in>) {
chomp $words;
my $last_duo_idx = length($words) - 2;
for my $i (0 .. $last_duo_idx) {
my $duo = substr($words, $i, 2);
++$wordcount{$duo};
}
}
my #skeys = sort { $wordcount{$b} <=> $wordcount{$a} } keys %wordcount;
foreach my $word (#skeys) {
print "$word\t$wordcount{$word}\n";
}
This runs correctly on a made-up file. (I sort separately only so to not run off of the page.)
Comments
Need to stop one before last in the line, and substr starts from 0; thus -2
One almost never needs a C-style loop
There is no need here to test for existence of a key. If it doesn't exist it is autovivified (created), then incremented to 1 with ++; otherwise the count is incremented.
To sort numerically use <=>, not cmp
Typos:
substr($words, $i; 2) needs a , not ;, so substr($words, $i, 2)
$wordcount{$duo} in print should be $wordcount{$word}.
I am not sure about naming: why is a line of text called $words?

Testing numeric user input against array elements

I'm making a simple fortune teller program for a class. I wanted to start by having the user choose between four numbers, like on a paper fortune teller (cootie catcher, as it were).
I created an array, #number_choices = ( 1, 2, 3, 4 ); and I wanted to make sure the user input was equal to one of the numbers in the array. Here is what I have so far, which is not working at all (when I run the program, it prints the error message no matter what number I enter, except for sometimes 2 or 1):
my $number_chosen = <STDIN>;
chomp ($number_chosen);
my $num;
my $found = 0;
while ( $found == 0 )
{
foreach $num (#number_choices)
{
if ($number_chosen == $num)
{
$found = 1;
last;
}
else
{
print "I'm sorry, that number is not valid. Please pick a number: " . join(', ', #number_choices) . "\n";
$number_chosen = <STDIN>;
chomp ($number_chosen);
}
}
}
You have a logic error. You choose a number but for every loop through the array it makes you choose another one, so if in the second loop you enter number 2 it will be right regardless of your first input, and same number 3 for third loop.
You should put the error message out of the foreach loop and ask for a number inside the while. Besides that, the last only goes out of the nearest loop, so you need to use a label to go out of the while. Something similar to following dirty solution:
my #number_choices = (1, 2, 3, 4);
my $num;
my $found = 0;
LOOP:
while ( $found == 0 )
{
$number_chosen = <STDIN>;
chomp ($number_chosen);
foreach $num (#number_choices)
{
if ($number_chosen == $num)
{
$found = 1;
last LOOP;
}
}
print "I'm sorry, that number is not valid. Please pick a number: " . join(', ', #number_choices) . "\n";
}

Perl How to use array store input strings

User first enter a number of lines. It then reads n lines of text from user input, and prints these lines backwards, i.e., if n=5, it prints the 5th
line first, the 4th, …, and the 1st,line last. I don't think wrong in my code, but when i start enter lines(line end with a newline), it won't stop. my array can store infinite number of lines which cause the problem stop them
use strict;
use warnings;
print "Enter number of n \n";
my $n = <STDIN>;
print "Enter couple lines of text \n";
my #array = (1..$n);
#array=<STDIN>;
do{
print "$array[$n]";
$n--;
}until($n=0);
Below are some tips that might help you:
Always include use strict; and use warnings at the top of your scripts to enforce good coding practices and help you find syntax errors sooner.
You must chomp your input from <STDIN> to remove return characters.
Use the array function push to add elements to the end of an array. Other relevant array functions include pop, shift, unshift, and potentially splice.
Use reverse to return an array of reversed order.
Finally, the for my $element (#array) { can be a helpful construct for iterating over the elements of an array.
These tips lead to the following code:
use strict;
use warnings;
print "Enter number of n \n";
chomp(my $n = <STDIN>);
die "n must be an integer" if $n =~ /^\d+$/;
my #array;
print "Enter $n lines of text\n";
for (1..$n) {
my $input = <STDIN>;
# chomp $input; # Do you want line endings, or not?
push #array, $input;
}
print "Here is your array: #array";
The end loop condition is do { … } until ($n = 0);, which is equivalent to do { … } while (!($n = 0));
The trouble is that the condition is an assignment, and zero is always false, so the loop is infinite.
Use do { … } until ($n == 0);.
Note that the input is in the line #array = <STDIN>; — it reads all the input provided until EOF. It is not constrained by the value of $n in any way.
#!/usr/bin/env perl
use strict;
use warnings;
print "Enter number of n \n";
my $n = <STDIN>;
printf "Got %d\n", $n;
print "Enter couple lines of text \n";
my #array = (1..$n);
#array = <STDIN>;
do {
print "$n = $array[$n]";
$n--;
} until ($n == 0);
When run, that gives:
$ perl inf.pl
Enter number of n
3
Got 3
Enter couple lines of text
abc
def
ghi
jkl
^D
3 = jkl
2 = ghi
1 = def
$
I think your expectations are skewiff.

I can't access hash values

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/>/) ...

Perl script problems

The purpose of the script is to process all words from a file and output ALL words that occur the most. So if there are 3 words that each occur 10 times, the program should output all the words.
The script now runs, thanks to some tips I have gotten here. However, it does not handle large text files (i.e. the New Testament). I'm not sure if that is a fault of mine or just a limitation of the code. I am sure there are several other problems with the program, so any help would be greatly appreciated.
#!/usr/bin/perl -w
require 5.10.0;
print "Your file: " . $ARGV[0] . "\n";
#Make sure there is only one argument
if ($#ARGV == 0){
#Make sure the argument is actually a file
if (-f $ARGV[0]){
%wordHash = (); #New hash to match words with word counts
$file=$ARGV[0]; #Stores value of argument
open(FILE, $file) or die "File not opened correctly.";
#Process through each line of the file
while (<FILE>){
chomp;
#Delimits on any non-alphanumeric
#words=split(/[^a-zA-Z0-9]/,$_);
$wordSize = #words;
#Put all words to lowercase, removes case sensitivty
for($x=0; $x<$wordSize; $x++){
$words[$x]=lc($words[$x]);
}
#Puts each occurence of word into hash
foreach $word(#words){
$wordHash{$word}++;
}
}
close FILE;
#$wordHash{$b} <=> $wordHash{$a};
$wordList="";
$max=0;
while (($key, $value) = each(%wordHash)){
if($value>$max){
$max=$value;
}
}
while (($key, $value) = each(%wordHash)){
if($value==$max && $key ne "s"){
$wordList.=" " . $key;
}
}
#Print solution
print "The following words occur the most (" . $max . " times): " . $wordList . "\n";
}
else {
print "Error. Your argument is not a file.\n";
}
}
else {
print "Error. Use exactly one argument.\n";
}
Your problem lies in the two missing lines at the top of your script:
use strict;
use warnings;
If they had been there, they would have reported lots of lines like this:
Argument "make" isn't numeric in array element at ...
Which comes from this line:
$list[$_] = $wordHash{$_} for keys %wordHash;
Array elements can only be numbers, and since your keys are words, that won't work. What happens here is that any random string is coerced into a number, and for any string that does not begin with a number, that will be 0.
Your code works fine reading the data in, although I would write it differently. It is only after that that your code becomes unwieldy.
As near as I can tell, you are trying to print out the most occurring words, in which case you should consider the following code:
use strict;
use warnings;
my %wordHash;
#Make sure there is only one argument
die "Only one argument allowed." unless #ARGV == 1;
while (<>) { # Use the diamond operator to implicitly open ARGV files
chomp;
my #words = grep $_, # disallow empty strings
map lc, # make everything lower case
split /[^a-zA-Z0-9]/; # your original split
foreach my $word (#words) {
$wordHash{$word}++;
}
}
for my $word (sort { $wordHash{$b} <=> $wordHash{$a} } keys %wordHash) {
printf "%-6s %s\n", $wordHash{$word}, $word;
}
As you'll note, you can sort based on hash values.
Here is an entirely different way of writing it (I could have also said "Perl is not C"):
#!/usr/bin/env perl
use 5.010;
use strict; use warnings;
use autodie;
use List::Util qw(max);
my ($input_file) = #ARGV;
die "Need an input file\n" unless defined $input_file;
say "Input file = '$input_file'";
open my $input, '<', $input_file;
my %words;
while (my $line = <$input>) {
chomp $line;
my #tokens = map lc, grep length, split /[^A-Za-z0-9]+/, $line;
$words{ $_ } += 1 for #tokens;
}
close $input;
my $max = max values %words;
my #argmax = sort grep { $words{$_} == $max } keys %words;
for my $word (#argmax) {
printf "%s: %d\n", $word, $max;
}
why not just get the keys from the hash sorted by their value and extract the first X?
this should provide an example: http://www.devdaily.com/perl/edu/qanda/plqa00016

Resources