Home > other >  Inserting colon with join function after splitting. PERL
Inserting colon with join function after splitting. PERL

Time:01-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.

CodePudding user response:

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.
  •  Tags:  
  • Related