Named Unary and File Test Operators

Some of the "functions" described in Chapter 29 are really unary operators. Table 3.2 lists all the named unary operators.

Table 3-2. Named Unary Operators

-X (file tests)gethostbynamelocaltimereturn
alarmgetnetbynamelockrmdir
callergetpgrplogscalar
chdirgetprotobynamelstatsin
chrootglobmysleep
cosgmtimeoctsqrt
definedgotoordsrand
deletehexquotemetastat
dointranduc
evallcreadlinkucfirst
existslcfirstrefumask
exitlengthrequireundef

Unary operators have a higher precedence than some of the binary operators. For example:

sleep 4 | 3;

does not sleep for 7 seconds; it sleeps for 4 seconds and then takes the return value of sleep (typically zero) and bitwise ORs that with 3, as if the expression were parenthesized as:

(sleep 4) | 3;

Compare this with:

print 4 | 3;

which does take the value of 4 ORed with 3 before printing it (7 in this case), as if it were written:

print (4 | 3);

This is because print is a list operator, not a simple unary operator. Once you've learned which operators are list operators, you'll have no trouble telling unary operators and list operators apart. When in doubt, you can always use parentheses to turn a named unary operator into a function. Remember, if it looks like a function, it is a function.

Another funny thing about named unary operators is that many of them default to $_ if you don't supply an argument. However, if you omit the argument but the token following the named unary operator looks like it might be the start of an ...

Get Programming Perl, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.