I am confused on this error. This program takes user input 1 2 3 2 and displays the input in a specific order.
#!/usr/bin/perl -w
use strict;
use warnings;
print "Enter a number :";
my $num = <STDIN>;
chomp($num);
my @final = split(' ',$num);
my @count;
foreach my $x (@final){
$count[my $x]++;
}
foreach my $x (@count){
print my $x .$count[my $x];
}
My output: I get this error:
"my" variable $x masks earlier declaration in same statement at line 19
Expected output:
You are using my
a little bit too often.
my
is used to declare a variable, for the current scope (usually a block {...}
).
To use the variable, you don't need the my
.
So, in your first loop, do:
$count[ $x ]++;
In the second loop:
print "$x: $count[ $x ]\n";