Iv4nT
Iv4nT

Reputation: 21

Inserting colon with join function after splitting. PERL


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

Answers (2)

Polar Bear
Polar Bear

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

TLP
TLP

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.

  • The variable @result should be $result. You would know this if you had use strict enabled.
  • You use = 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.
  • You have a variable $value, which you move to $fruit, which you move to $ratio. This is confusing and pointless.
  • You cannot use join with just one value. Then it does nothing, as you need at least 2 values to join.
  • The output from your code is My ratio = 1My ratio = 2, not My ratio = 12.

Upvotes: 1

Related Questions