Named Unary and File Test Operators

Some of the “functions” described in Chapter 27 are really unary operators. Table 3-2 lists all the named unary operators.

Table 3-2. Named unary operators

X (file tests)filenolocksetnetent
absgetclogsetprotoent
alarmgetgrgidlstatsetservent
callergetgrnammyshift
chdirgethostbynameoctsin
chompgetnetbynameordsleep
chopgetpeernameoursqrt
chrgetpgrppopsrand
chrootgetprotobynameposstat
closegetpwnamprototypestate
closedirgetpwuidquotemetastudy
cosgetsocknamerandtell
dbmcloseglobreaddirtelldir
definedgmtimereadlinetied
deletehexreadlinkuc
dointreadpipeucfirst
eachkeysrefumask
eoflcresetundef
evallcfirstrewinddiruntie
existslengthrmdirvalues
exitlocalscalarwrite
explocaltimesethostentany ($) sub
fc   

Unlike list operators, 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 ...

Get Programming Perl, 4th Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.