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

Suppose i decalre a string my $x = "Expected value is",$y + 2; It gives me awarning message: Useless use of addition (+) in void context at above line; Can anyone answer how to avoid the warning message
  • Comment on declare string with addition of two variables

Replies are listed 'Best First'.
Re: declare string with addition of two variables
by bobf (Monsignor) on Sep 14, 2006 at 04:03 UTC

    It looks like you're trying to concatenate the results of $y + 2 to the previous string and assign the entire result to $x. If that's the case, you need to use the concatenation operator "." (see perlop) or join, not the comma operator. Your current code assigns "Expected value is" to $x and then sums $y + 2 but does not use the result of the summation. Try one of these:

    $x = "Expected value is " . ($y + 2); $x = join( ' ', "Expected value is", $y + 2 );

    Update: Note that "." and "+" have equal precedence (see perlop), so the parentheses are needed to ensure that the sum is concatenated to the string, not just the value of $y.

Re: declare string with addition of two variables
by graff (Chancellor) on Sep 14, 2006 at 04:24 UTC
    sprintf is also good for this sort of thing:
    $x = sprintf "Expected value is %d", $y + 2;
    You could put parens around the args for sprintf (I do, just about every time I use it, and just out of habit from my C coding days), but they are optional.
Re: declare string with addition of two variables
by Zaxo (Archbishop) on Sep 14, 2006 at 04:17 UTC

    You can also make concatenation implicit by getting the sum to evaluate inside interpolating quotes:

    my $x = "Expected value is ${\($y + 2)}";
    Some people hate that, but I think it adds flavor,

    After Compline,
    Zaxo

      If you're going to do that at least use the slightly more symmetrical @{[ $y + 2 ]}.

      Come on people! Aesthetics! We want eye-pleasing line noise.

      :)

      that thing seems to be working. Thanks for the reply.
Re: declare string with addition of two variables
by GrandFather (Saint) on Sep 14, 2006 at 04:09 UTC

    If you can answer "what are you trying to achieve", we may be able to answer your question. If you are simply declaring two initialised variables then:

    my $x = "Expected value is"; my $y = 2;

    is the way to do it. However I'd expect $y would cause trouble in your code in that case - you do include use strict; in your script don't you?

    If you are trying to increment $y and concatenate the result on to the end of the string then you need something like:

    my $x = "Expected value is " . ($y + 2);

    Note that the () are required.


    DWIM is Perl's answer to Gödel