monorels has asked for the wisdom of the Perl Monks concerning the following question:

Hi. Tell my please. Why this don't work? Thanks.

sub example { do { $av = irand(20) +1; $bv = irand(11) +1; $cv = (irand(2))?"+":"-"; } until (!($av $cv $bv >= 0 && $av $cv $bv <= 20)); print $av $cv $bv; }

gen.pl|38| Scalar found where operator expected at /home/monorels/iperl/gen.pl line 38, near "$cv $bv" (Missing operator before $bv?) 3 gen.pl|38| Scalar found where operator expected at /home/monorels/iperl/gen.pl line 38, near "$av $cv" (Missing operator before $cv?) 4 gen.pl|38| Scalar found where operator expected at /home/monorels/iperl/gen.pl line 38, near "$cv $bv" (Missing operator before $bv?) 5 gen.pl|39| Scalar found where operator expected at /home/monorels/iperl/gen.pl line 39, near "$cv $bv" (Missing operator before $bv?) 6 gen.pl|38| syntax error at /home/monorels/iperl/gen.pl line 38, near "$av $cv " 7 gen.pl|39| syntax error at /home/monorels/iperl/gen.pl line 39, near "$cv $bv"

Replies are listed 'Best First'.
Re: cv = (irand(2))?"+":"-";
by Corion (Patriarch) on Apr 05, 2016 at 08:20 UTC

    Have you read the error message? What part of the error message is unclear?

    Maybe now it's time to familiarize yourself with Perl and the Perl syntax.

    Can you explain in English what the expression is supposed to do that Perl complains about?

    $av $cv $bv

      It works:

      sub example { do { $av = irand(11) + 10; $bv = irand(11); $cv = irand(2) ? "+" : "-"; } until ( !( $av - $bv < 0 || $av + $bv >= 20 ) ); print $av. $cv . $bv . " = \n"; }
        Your print could be written more succinctly as
        print "$av$cv$bv = \n";
        For delimiters that interpolate like double quotes, blackslashed characters are converted to the appropriate whitespace or control character and scalars ($) and arrays (@) are converted to their contents as strings. See Quote and Quote like Operators in perlop for detail.

        #11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.

      my $x = 1; my $y = 2; my $z = "+"; print $x $z $y;

      I do not understand where the error is.

        Variables cannot stand in for operators. Again, you're sort of just making syntax up as you imagine it ought to be. Reading perlintro may help you to bring your expectations in line with the reality of the language.


        Dave

        my $x = 1; my $y = 2; my $z = "+"; print $x.$z.$y;

        I'm understand. <\p>