Reputation: 21
my $fruit;
my $quantity = <STDIN>;
my $results = split(/,|:/,$quantity);
foreach my $result(@results){
my ($fruit_name, $value) = split("=", @result);
if($fruit_name == "apple") {
$fruit = $value;
my $ratio = join(":", $fruit);
print "My ratio = $ratio";
}
}
My Output is: My ratio = 12 from the input: apple=1,apple=2.
My output that I wanted:
My ratio = 1:2.
Thank you for all your helps.
Upvotes: 1
Views: 84
Reputation: 6818
As an alternative for code simplicity you can use hashref to an array for fruits.
use strict;
use warnings;
use feature 'say';
my($fruit,$item,$count);
for( split(',',<DATA>) ) {
($item,$count) = split('=',$_);
push @{$fruit->{$item}}, $count;
}
say "My ratio = " . join(':', @{$fruit->{apple}});
__DATA__
apple=1,apple=2
Output
My ratio = 1:2
Upvotes: 1
Reputation: 67940
Mayhaps this is what you are looking to do
use strict;
use warnings;
use feature 'say';
chomp(my $quantity = <DATA>); # chomp removes newline from input
my @results = split /[,:]/, $quantity; # using [] to create a character class
my @nums;
foreach my $result (@results){
my ($fruit_name, $value) = split "=", $result;
if ($fruit_name eq "apple") { # have to use eq when comparing strings
push @nums, $value; # store value for later printing
}
}
say "My ratio = ", join ":", @nums;
__DATA__
apple=1,apple=2
Output:
My ratio = 1:2
Your code has these errors.
@result
should be $result
. You would know this if you had use strict
enabled.=
assignment where you wanted to use numerical equality test ==
. Since you did not use use warnings
, you didn't know about that. Also, you should use eq
for strings.$value
, which you move to $fruit
, which you move to $ratio
. This is confusing and pointless.join
with just one value. Then it does nothing, as you need at least 2 values to join.My ratio = 1My ratio = 2
, not My ratio = 12
.Upvotes: 1