Symbolic unary operators in Perl refer to unary operators represented by symbols.
Unary operators work on a single operand. Symbolic unary operators in Perl include:
The not operator is represented by
!. We use this operator for logical negation.
This means that when
! is appended before a boolean variable or expression, it flips the result.
# ! operator $n = 0; $result = !$n; print "Result is: ", $result;
The unary plus operator has little effect. It is represented by
Primarily, we use unary
+ to separate a function name from a parenthesized expression that would otherwise be interpreted as the complete list of function arguments.
# The unary + operator print "Without +: "; print (5) * 7; # (print 5) * 7 print "\n"; print "With +: "; print +(5) * 7; # print (5 * 7)
+, the second part of the expression is ignored, and only
5 is printed.
+, we are able to pass the entire expression as an argument to the
35, is printed.
The unary minus operator performs arithmetic negation if the operand is numeric.
If the operand is an identifier, a string is returned that consists of the minus sign followed by the identifier. If the string starts with a plus or minus, a string starting with the opposite sign is returned.
A basic effect of these rules is that -someword is equivalent to “-someword”.
All of this behavior is shown in the code below.
# The unary - operator $numeric = 10; print "With '-': ", -$numeric; print "\n"; $identifier = "Hello"; print "With '-': ", -$identifier; print "\n"; $opposite = "+World"; print "With '-': ", -$opposite; print "\n"; print -someword
The complement operator is used for bitwise negation. It is represented by
Bitwise negation may also be referred to as 1’s complement. Simply put, all the bits in the output are flipped to obtain the final result. The final result is the decimal equivalent of the binary representation.
The result of this operation varies according to the type of machine you are using (32 or 64 bit). Remember, all the bits are flipped, so the result might be a lot different from what you expect.
# The ~ operator $six = 6; # 110 $seven = 7; # 111 $output = $six & $seven; # 000...110 (6) $result = ~$output; # 111...001 print "Result is: ", ~$output;
The backslash operator creates a reference to whatever follows it. It is represented by
\, we can create a reference to any named variable or subroutine.
If applied to a list, the
\ operator generates a whole list of references.
# The \ operator $scalar = \$edpressp; # a scalar ref $const = \1133; # a constant ref $array = \@arr; # an array ref $hash = \%hash; # a hash ref
View all Courses