How is a for loop written in Perl? - perl

How do you write a for loop in Perl? I've tried the following to no avail:
my $i = 0;
for my $foo; do
$i=$[i+1];
done < bar;

There are two types of for loop in perl, in addition to the for statement modifier. They look like this:
# c-style for loop
for ( my $i = 0; $i < 12; ++$i ) {
...
}
# regular for loop
for my $i (0..11) {
...
}
# statement modifier
... for 0..11;

To write a for loop in Perl the syntax would look like this:
for my $foo (#array) {
print "$foo\n";
}

The syntax of a for loop in Perl is:
for ( init; condition; increment )
{
statement(s);
}
Example:
for (my $i=0; $i <= 9; $i++)
{
print "$i\n";
}

for
for(my $i = 1; $i < 5; $i++) {
something...
}
or foreach
my #names = qw(Steve Bill Connor Bradley);
foreach my $name (#names) {
something...
}

Related

How do I fix this (perl) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed last month.
Improve this question
Here's the code; it's in Perl.
use warnings;
use strict;
use Data::Dumper;
print "I'll show the prime numbers between 2 and u numbers for you.\n";
print "Pls, enter u numbers.";
my $numberer = <STDIN>;
my #nonprime = qw();
my #all = qw();
for (my $i = 3; $i < $numberer; $i++) {
my $lenght = #all;
$all[$lenght] = $i;
for (my $i = 3; $i < $numberer; $i++) {
if ($numberer <= 3) {
print "It's none.";
} else {
for (my $i = 3; $i < $numberer; $i++) {
for (my $j = 2; $j < $numberer; $j++) {
if ($i == $j) {
} elsif ($i % $j == 0) {
my $len = #nonprime;
$nonprime[$len] = $i;
} else {
}
}
}
}
my %h;
#h{#nonprime} = #nonprime;
print Dumper [grep {!exists $h{$_}} #all];
Can you help me by explaining what the problem is? I try to learn perl programming and do some exercise that is "Write your own program to capture all the prime numbers between 2 and a number the user
gives you."
Might be this code will help you for your question.
#!/usr/bin/perl
use warnings;
use strict;
sub testprime
{
my $m = shift #_;
my $i = 2;
while ($i < $m)
{
return 0 unless ($m % $i++);
}
return 1;
}
print "Enter a number to find the prime \n";
chomp (my $n = <STDIN>);
system 'cls';
for(my $i=2; $i<=$n; $i++)
{
my $FindPrime = testprime $i;
if ( $FindPrime == 1)
{
print "Yes, the given number - $i is Prime \n";
}
else
{
print "No, It is NOT a prime Number - $i \n";
}
}
Thnx.

Unable to modify array parameter

This is supposed to put the contents of nums into decreasing order, however sort does not change the contents of nums. Many sites I read have said to pass by reference, but I don't think I'm dereferencing the argument correctly. Bear with me, this is my first Perl program :)
#! /usr/bin/env perl
sub sort {
my #arr = #_;
my $len = scalar #arr;
for (my $i = 1; $i < $len-1; $i = $i + 1) {
my $max = $i;
for (my $j = $i + 1; $j < $len; $j = $j + 1) {
if ($arr[$j] > $arr[$max]) {
$max = $j
}
}
$temp = $arr[$max];
$arr[$max] = $arr[$i];
$arr[$i] = $temp;
}
}
print "Enter 10 numbers: ";
my $numbers = <STDIN>;
my #nums = split ' ', $numbers;
print "Unsorted: #nums\n";
sort \#nums;
print "Sorted: #nums\n";
#Matt Jacob helped me out with this one. This is what I was looking for.
#! /usr/bin/env perl
sub selection_sort {
my $arr = shift;
my $len = scalar #$arr;
for (my $i = 0; $i < $len-1; $i++) {
my $max = $i;
for (my $j = $i + 1; $j < $len; $j++) {
if (#$arr[$j] > #$arr[$max]) {
$max = $j
}
}
my $temp = #$arr[$max];
#$arr[$max] = #$arr[$i];
#$arr[$i] = $temp;
}
}
print "Enter 10 numbers: ";
my $input = <STDIN>;
my #integers = split ' ', $input;
print "Unsorted: #integers\n";
selection_sort \#integers;
print "Sorted: #integers\n";

Perl Script not running correctly

When ever I run this bit of code. it doesn't display any output. Anyone see anything wrong?
I am trying to display this in the out put:
A
AA
AAA
AAAB
AAABA
AAABAA
AAABAAA
AAABAAAB
etc.
#!/usr/local/bin/perl
$A = 3;
$B = 1;
$i = 1;
$output = "";
$j = 1;
while ($i <= $ARGV[0]) {
while ($j <= $i) {
if ($A == 0 && $B == 0) {
$A = 3;
$B = 1;
}
if ($A > 0) {
$output.= "A";
$A--;
}
else {
$output.= "B";
$B--;
}
$j++;
}
print($output . "\n");
$i++;
}
It works for me when I run it with a numeric argument (number of lines).
An idea how to simplify the code:
#!/usr/bin/perl
use warnings;
use strict;
my $count = shift;
my $A = 3;
my $B = 1;
my $string = q();
$string .= ('A' x $A) . ('B' x $B) while $count > length $string;
print substr($string, 0, $_), "\n" for 1 .. $count;
It uses a different algorithm - it creates the longest possible string, and then outputs parts of it.
if there is no #ARGV, while ($i <= $ARGV[0]) never runs.
#ARGV is an array of the command line arguments provided when the script is executed. you did not provide any command line arguments. if you had use warnings in effect, you would be warned that $ARGV[0] is uninitialized.
As from ikegami comment. You cann't pass the input at when the program is compile. For example, consider your file name is algo.pl. Can you run your program with
perl algo.pl 10
Here 10 is the input value of the program. In program value is retrieve by the $ARGV[0]
so in your program looks like while ($i <= $ARGV[0]).
If you want pass the several values like perl filename.pl 12 data1 data2In your data retrieve by $ARGV[0] $ARGV[1] $ARGV[2] for more information see here.
If you want pass the input at the time of execution used STDIN
use warnings;
use strict;
my $A = 3;
my $B = 1;
my $i = 1;
my $output = "";
my $j = 1;
print "Enter the value: ";
chomp(my $value = <STDIN>);
while ($i <= $value) {
while ($j <= $i) {
if ($A == 0 && $B == 0) {
$A = 3;
$B = 1;
}
if ($A > 0) {
$output.= "A";
$A--;
}
else {
$output.= "B";
$B--;
}
$j++;
}
print($output . "\n");
$i++;
}

Perl - Trouble With Loop Variables

I'm fairly new to coding in Perl and am used to using C-style for loops. I'm not sure why the following program never prints a value of 4 for $l:
use strict;
use warnings;
my $minL = 4;
for (my $l = $minL; $l > 0; $l--) {
for (my $i = 0; $i + $l < $minL; $i++) {
print "$i $l\n";
}
}
Many thanks in advance.
Your inner for loop has the condition $i + $l < $minL. If $l == $minL, then $i + $l < $minL will be false even if $i is 0, so the loop runs 0 times and never prints anything.
Maybe you wanted to use <= for the condition?
By the way, here is how you could write the same thing (assuming the <= condition) using Perl-style foreach loops:
my $minL = 4;
for my $l (reverse 1 .. $minL) {
for my $i (0 .. $minL - $l) {
print "$i $l\n";
}
}
In the first iteration:
for (my $l = $minL; $l > 0; $l--) {
$l == $minL
for (my $i = 0; $i + $l < $minL; $i++) {
So this block won't run until $l is decremented:
print "$i $l\n";
}
Change your inner loop to:
for (my $i = 0; $i + $l <= $minL; $i++) {

Best way to alternate a variable value in loop? (Perl)

my #arr = (1,2,3,4,5,6,7,8,9);
my $counter = 0;
foreach my $a (#arr) {
my $str;
if ($counter % 2 == 0) {
$str = 'hi';
} else {
$str = 'bye';
}
print $str . "\n";
$counter++;
}
What is the best way to alternate between two different values for each iteration of a while loop? Simple example above, is there a better way than keeping a counter and modding to find even values?
my #arr = qw( a b c );
for my $i (0..$#arr) {
print "$arr[$i] ", $i % 2 ? 'bye' : 'hi', "\n";
}
Good name.
my /*boolean*/ $even = 0;
foreach ...
next if ... # skipping line
$even = !$even;
... # work
print $even ? 'hi' : 'bye';
I'd do like this:
...
my #arr = (1..9);
for (my $i=0; $i<scalar(#arr); $i++) {
my $str = ($i % 2 == 0) ? 'hi' : 'bye';
print "$str\n";
}
my ($foo, $bar) = qw(foo bar);
for (0..10) {
print "$foo\n";
($foo, $bar) = ($bar, $foo);
}
A weird one, but no counters and no modding to find even values:
use strict;
sub foo {
shift || return and bar(#_);
print "doing something with Value2 \n";
}
sub bar {
shift || return and foo(#_);
print "doing something with Value1 \n";
}
foo(1..100);
Do whatever you want by calling foo() or bar() and chosing an even or odd values insted of 100. Maybe you would like to use $#arr insted of hardcoded values and so on.
But please don't write code like this.
Couldn't resist:
my #arr = (1,2,3,4,5,6,7,8,9);
my #alt = qw( hi bye );
my $counter = 0;
foreach my $a (#arr) {
print $alt[($counter++ % 2)] . "\n";
}
Or per dolmen's comment using "&" which should be more efficient compared to modulo (%)
my #arr = (1,2,3,4,5,6,7,8,9);
my #alt = qw( hi bye );
my $counter = 0;
foreach my $a (#arr) {
print $alt[($counter++ & 1)] . "\n";
}