Search code examples
rakucommaide

Raku vs. Perl5, an unexpected result


When I run this script in Raku I get the letter A with several newlines. Why do I not get the concatenated strings as expected (and as Perl5 does) ?

EDIT BTW can I compile in commaIDE the file with the Perl5 compiler, where can I change this compiler to be that of Perl5 ?

say "A";

my $string1  = "00aabb";
my $string2  = "02babe";

say join ("A", $string1, $string2);
print "\n";

my @strings = ($string1, $string2);

say join ("A", @strings);
print "\n";

Solution

  • The solution I suggest is to drop the parens:

    say "A";
    
    my $string1  = "00aabb";
    my $string2  = "02babe";
    
    say join "A", $string1, $string2;     # Pass THREE arguments to `join`, not ONE
    print "\n";
    
    my @strings = $string1, $string2;
    
    say join "A", @strings;
    print "\n";
    

    (The elements in @strings in the second call to join are flattened, thus acting the same way as the first call to join.)

    The above code displays:

    A
    00aabbA02babe
    
    00aabbA02babe
    
    

    When I run this script in Raku I get the letter A with several newlines.

    Your code calls join with ONE argument, which is the joiner, and ZERO strings to concatenate. So the join call generates null strings. Hence you get blank lines.

    Why do I not get the concatenated strings

    The two say join... statements in your code print nothing but a newline because they're like the third and fourth say lines below:

    say join(  " \o/ ", "one?", "two?" ); # one? \o/ two?␤
    
    say join   " \o/ ", "one?", "two?"  ; # one? \o/ two?␤
    
    say join ( " \o/ ", "one?", "two?" ); # ␤
    
    say join(  " \o/  one? two?"       ); # ␤
    

    The first and second lines above pass three strings to join. The third passes a single List which then gets coerced to become a single string (a concatenation of the elements of the List joined using a single space character), i.e. the same result as the fourth line.


    The my @strings = ($string1, $string2); incantation happens to work as you intended, because an assignment to a "plural" variable on the left hand side of the = will iterate the value, or list of values, on the right hand side.

    But it's a good habit in Raku to err on the side of avoiding redundant code, in this instance only using parens if you really have to use them to express something different from code without them. This is a general principle in Raku that makes code high signal, low noise. For your code, all the parens are redundant.