Operator unary minus
- in Perl
If unary minus is applied to a number or to a string which contains
number, then the operation result is a number with an opposite sign (except for a situation with zero,
about it in the next section).
Here is an example. This code will display
-3 (no error and no
warnings will not):
-3, which we have received — this is the number
-3, not the line
If you apply the unary minus to the number
0 or row
'0', the result will be the number
If you apply the unary minus to the identifier, the result will be a string consisting of a minus and this
ID. In this example, the variable
$var is line
'-asdf'. No errors and
my $var = - asdf;
The identifier must begin with an underscore or with a letter. Here's the code that uses
digit as the first character:
my $var = - 3asdf;
This code will generate an error:
Bareword found where operator expected at script.pl line 3, near "3asdf"
(Missing operator before asdf?)
syntax error at script.pl line 3, near "3asdf"
Execution of script.pl aborted due to compilation errors.
A string with a number, which begins with the character
print -'+44', "\n";
print -'-44', "\n";
The result of this code depends on the version of Perl. 5.8, 5.10, 5.12 displays the first line
-44, and the second
Since 5.14 the second line will
44 without plus.
And here's a code example, generally has 3 different ways, depending on the Perl version:
print -'+0', "\n";
print -'-0', "\n";
5.8, 5.10, 5.12 displays
+0, Version 5.14 and 5.16 displays two zeros. And since 5.18 on the screen
The line that begins with the character
In the case if you apply the unary minus to the line that starts with a plus or
minus, the result is a string that begins with another character. Here's an example:
The program will display:
A string that does not begin with a
In this situation, Perl will try to convert a string to a number.
The result of the code above is a warning and the number
Argument "3.8asdf" isn't numeric in negation (-) at script.pl line 6.
Here's a snippet of the output
perldoc perlop about the unary minus:
Unary "-" performs arithmetic negation if the operand is numeric,
including any string that looks like a number. If the operand is an
identifier, a string consisting of a minus sign concatenated with the
identifier is returned. Otherwise, if the string starts with a plus or
minus, a string starting with the opposite sign is returned. One effect of
these rules is that "-bareword" is equivalent to the string "-bareword".
If, however, the string begins with a non-alphabetic character (excluding
"+" or "-"), Perl will attempt to convert the string to a numeric, and the
arithmetic negation is performed. If the string cannot be cleanly
converted to a numeric, Perl will give the warning Argument "the string"
isn't numeric in negation (-) at ....