Cari di Perl 
    Perl Manual
Daftar Isi
(Sebelumnya) Daftar IsiAssignment Operators (Berikutnya)

Perl Operators

Daftar Isi

NAME

perlop - Perl operators and precedence

DESCRIPTION

Operator Precedence and Associativity

Operator precedence and associativity work in Perl more or less likethey do in mathematics.

Operator precedence means some operators are evaluated beforeothers. For example, in 2 + 4 * 5, the multiplication has higherprecedence so 4 * 5 is evaluated first yielding 2 + 20 ==22 and not 6 * 5 == 30.

Operator associativity defines what happens if a sequence of thesame operators is used one after another: whether the evaluator willevaluate the left operations first or the right. For example, in 8- 4 - 2, subtraction is left associative so Perl evaluates theexpression left to right. 8 - 4 is evaluated first making theexpression 4 - 2 == 2 and not 8 - 2 == 6.

Perl operators have the following associativity and precedence,listed from highest precedence to lowest. Operators borrowed fromC keep the same precedence relationship with each other, even whereC's precedence is slightly screwy. (This makes learning Perl easierfor C folks.) With very few exceptions, these all operate on scalarvalues only, not array values.

  1. leftterms and list operators (leftward)
  2. left->
  3. nonassoc++ --
  4. right**
  5. right! ~ \ and unary + and -
  6. left=~ !~
  7. left* / % x
  8. left+ - .
  9. left<< >>
  10. nonassocnamed unary operators
  11. nonassoc< > <= >= lt gt le ge
  12. nonassoc== != <=> eq ne cmp ~~
  13. left&
  14. left| ^
  15. left&&
  16. left|| //
  17. nonassoc.. ...
  18. right?:
  19. right= += -= *= etc.
  20. left, =>
  21. nonassoclist operators (rightward)
  22. rightnot
  23. leftand
  24. leftor xor

In the following sections, these operators are covered in precedence order.

Many operators can be overloaded for objects. See overload.

Terms and List Operators (Leftward)

A TERM has the highest precedence in Perl. They include variables,quote and quote-like operators, any expression in parentheses,and any function whose arguments are parenthesized. Actually, therearen't really functions in this sense, just list operators and unaryoperators behaving as functions because you put parentheses aroundthe arguments. These are all documented in perlfunc.

If any list operator (print(), etc.) or any unary operator (chdir(), etc.)is followed by a left parenthesis as the next token, the operator andarguments within parentheses are taken to be of highest precedence,just like a normal function call.

In the absence of parentheses, the precedence of list operators such asprint, sort, or chmod is either very high or very low depending onwhether you are looking at the left side or the right side of the operator.For example, in

  1. @ary = (1, 3, sort 4, 2);
  2. print @ary;# prints 1324

the commas on the right of the sort are evaluated before the sort,but the commas on the left are evaluated after. In other words,list operators tend to gobble up all arguments that follow, andthen act like a simple TERM with regard to the preceding expression.Be careful with parentheses:

  1. # These evaluate exit before doing the print:
  2. print($foo, exit);# Obviously not what you want.
  3. print $foo, exit;# Nor is this.
  4. # These do the print before evaluating exit:
  5. (print $foo), exit;# This is what you want.
  6. print($foo), exit;# Or this.
  7. print ($foo), exit;# Or even this.

Also note that

  1. print ($foo & 255) + 1, "\n";

probably doesn't do what you expect at first glance. The parenthesesenclose the argument list for print which is evaluated (printingthe result of $foo & 255). Then one is added to the return valueof print (usually 1). The result is something like this:

  1. 1 + 1, "\n"; # Obviously not what you meant.

To do what you meant properly, you must write:

  1. print(($foo & 255) + 1, "\n");

See Named Unary Operators for more discussion of this.

Also parsed as terms are the do {} and eval {} constructs, aswell as subroutine and method calls, and the anonymousconstructors [] and {}.

See also Quote and Quote-like Operators toward the end of this section,as well as I/O Operators.

The Arrow Operator

"->" is an infix dereference operator, just as it is in Cand C++. If the right side is either a [...], {...}, or a(...) subscript, then the left side must be either a hard orsymbolic reference to an array, a hash, or a subroutine respectively.(Or technically speaking, a location capable of holding a hardreference, if it's an array or hash reference being used forassignment.) See perlreftut and perlref.

Otherwise, the right side is a method name or a simple scalarvariable containing either the method name or a subroutine reference,and the left side must be either an object (a blessed reference)or a class name (that is, a package name). See perlobj.

Auto-increment and Auto-decrement

"++" and "--" work as in C. That is, if placed before a variable,they increment or decrement the variable by one before returning thevalue, and if placed after, increment or decrement after returning thevalue.

  1. $i = 0; $j = 0;
  2. print $i++; # prints 0
  3. print ++$j; # prints 1

Note that just as in C, Perl doesn't define when the variable isincremented or decremented. You just know it will be done sometimebefore or after the value is returned. This also means that modifyinga variable twice in the same statement will lead to undefined behavior.Avoid statements like:

  1. $i = $i ++;
  2. print ++ $i + $i ++;

Perl will not guarantee what the result of the above statements is.

The auto-increment operator has a little extra builtin magic to it. Ifyou increment a variable that is numeric, or that has ever been used ina numeric context, you get a normal increment. If, however, thevariable has been used in only string contexts since it was set, andhas a value that is not the empty string and matches the pattern/^[a-zA-Z]*[0-9]*\z/, the increment is done as a string, preserving eachcharacter within its range, with carry:

  1. print ++($foo = "99");# prints "100"
  2. print ++($foo = "a0");# prints "a1"
  3. print ++($foo = "Az");# prints "Ba"
  4. print ++($foo = "zz");# prints "aaa"

undef is always treated as numeric, and in particular is changedto 0 before incrementing (so that a post-increment of an undef valuewill return 0 rather than undef).

The auto-decrement operator is not magical.

Exponentiation

Binary "**" is the exponentiation operator. It binds even moretightly than unary minus, so -2**4 is -(2**4), not (-2)**4. (This isimplemented using C's pow(3) function, which actually works on doublesinternally.)

Symbolic Unary Operators

Unary "!" performs logical negation, that is, "not". See also not for a lowerprecedence version of this.

Unary "-" performs arithmetic negation if the operand is numeric,including any string that looks like a number. If the operand isan identifier, a string consisting of a minus sign concatenatedwith the identifier is returned. Otherwise, if the string startswith a plus or minus, a string starting with the opposite sign isreturned. One effect of these rules is that -bareword is equivalentto the string "-bareword". If, however, the string begins with anon-alphabetic character (excluding "+" or "-"), Perl will attempt to convertthe string to a numeric and the arithmetic negation is performed. If thestring cannot be cleanly converted to a numeric, Perl will give the warningArgument "the string" isn't numeric in negation (-) at ....

Unary "~" performs bitwise negation, that is, 1's complement. Forexample, 0666 & ~027 is 0640. (See also Integer Arithmetic andBitwise String Operators.) Note that the width of the result isplatform-dependent: ~0 is 32 bits wide on a 32-bit platform, but 64bits wide on a 64-bit platform, so if you are expecting a certain bitwidth, remember to use the "&" operator to mask off the excess bits.

When complementing strings, if all characters have ordinal values under256, then their complements will, also. But if they do not, allcharacters will be in either 32- or 64-bit complements, depending on yourarchitecture. So for example, ~"\x{3B1}" is "\x{FFFF_FC4E}" on32-bit machines and "\x{FFFF_FFFF_FFFF_FC4E}" on 64-bit machines.

Unary "+" has no effect whatsoever, even on strings. It is usefulsyntactically for separating a function name from a parenthesized expressionthat would otherwise be interpreted as the complete list of functionarguments. (See examples above under Terms and List Operators (Leftward).)

Unary "\" creates a reference to whatever follows it. See perlreftutand perlref. Do not confuse this behavior with the behavior ofbackslash within a string, although both forms do convey the notionof protecting the next thing from interpolation.

Binding Operators

Binary "=~" binds a scalar expression to a pattern match. Certain operationssearch or modify the string $_ by default. This operator makes that kindof operation work on some other string. The right argument is a searchpattern, substitution, or transliteration. The left argument is what issupposed to be searched, substituted, or transliterated instead of the default$_. When used in scalar context, the return value generally indicates thesuccess of the operation. The exceptions are substitution (s///)and transliteration (y///) with the /r (non-destructive) option,which cause the return value to be the result of the substitution.Behavior in list context depends on the particular operator.See Regexp Quote-Like Operators for details and perlretut forexamples using these operators.

If the right argument is an expression rather than a search pattern,substitution, or transliteration, it is interpreted as a search pattern at runtime. Note that this means that its contents will be interpolated twice, so

  1. '\' =~ q'\';

is not ok, as the regex engine will end up trying to compile thepattern \, which it will consider a syntax error.

Binary "!~" is just like "=~" except the return value is negated inthe logical sense.

Binary "!~" with a non-destructive substitution (s///r) or transliteration(y///r) is a syntax error.

Multiplicative Operators

Binary "*" multiplies two numbers.

Binary "/" divides two numbers.

Binary "%" is the modulo operator, which computes the divisionremainder of its first argument with respect to its second argument.Given integeroperands $a and $b: If $b is positive, then $a % $b is$a minus the largest multiple of $b less than or equal to$a. If $b is negative, then $a % $b is $a minus thesmallest multiple of $b that is not less than $a (that is, theresult will be less than or equal to zero). If the operands$a and $b are floating point values and the absolute value of$b (that is abs($b)) is less than (UV_MAX + 1), onlythe integer portion of $a and $b will be used in the operation(Note: here UV_MAX means the maximum of the unsigned integer type).If the absolute value of the right operand (abs($b)) is greater thanor equal to (UV_MAX + 1), "%" computes the floating-point remainder$r in the equation ($r = $a - $i*$b) where $i is a certaininteger that makes $r have the same sign as the right operand$b (not as the left operand $a like C function fmod())and the absolute value less than that of $b.Note that when use integer is in scope, "%" gives you direct accessto the modulo operator as implemented by your C compiler. Thisoperator is not as well defined for negative operands, but it willexecute faster.

Binary "x" is the repetition operator. In scalar context or if the leftoperand is not enclosed in parentheses, it returns a string consistingof the left operand repeated the number of times specified by the rightoperand. In list context, if the left operand is enclosed inparentheses or is a list formed by qw/STRING/, it repeats the list.If the right operand is zero or negative, it returns an empty stringor an empty list, depending on the context.

  1. print '-' x 80;# print row of dashes
  2. print "\t" x ($tab/8), ' ' x ($tab%8);# tab over
  3. @ones = (1) x 80;# a list of 80 1's
  4. @ones = (5) x @ones;# set all elements to 5

Additive Operators

Binary + returns the sum of two numbers.

Binary - returns the difference of two numbers.

Binary . concatenates two strings.

Shift Operators

Binary << returns the value of its left argument shifted left by thenumber of bits specified by the right argument. Arguments should beintegers. (See also Integer Arithmetic.)

Binary >> returns the value of its left argument shifted right bythe number of bits specified by the right argument. Arguments shouldbe integers. (See also Integer Arithmetic.)

Note that both << and >> in Perl are implemented directly using<< and >> in C. If use integer (see Integer Arithmetic) isin force then signed C integers are used, else unsigned C integers areused. Either way, the implementation isn't going to generate resultslarger than the size of the integer type Perl was built with (32 bitsor 64 bits).

The result of overflowing the range of the integers is undefinedbecause it is undefined also in C. In other words, using 32-bitintegers, 1 << 32 is undefined. Shifting by a negative numberof bits is also undefined.

If you get tired of being subject to your platform's native integers,the use bigint pragma neatly sidesteps the issue altogether:

  1. print 20 << 20; # 20971520
  2. print 20 << 40; # 5120 on 32-bit machines,
  3. # 21990232555520 on 64-bit machines
  4. use bigint;
  5. print 20 << 100; # 25353012004564588029934064107520

Named Unary Operators

The various named unary operators are treated as functions with oneargument, with optional parentheses.

If any list operator (print(), etc.) or any unary operator (chdir(), etc.)is followed by a left parenthesis as the next token, the operator andarguments within parentheses are taken to be of highest precedence,just like a normal function call. For example,because named unary operators are higher precedence than ||:

  1. chdir $foo || die;# (chdir $foo) || die
  2. chdir($foo) || die;# (chdir $foo) || die
  3. chdir ($foo) || die;# (chdir $foo) || die
  4. chdir +($foo) || die;# (chdir $foo) || die

but, because * is higher precedence than named operators:

  1. chdir $foo * 20;# chdir ($foo * 20)
  2. chdir($foo) * 20;# (chdir $foo) * 20
  3. chdir ($foo) * 20;# (chdir $foo) * 20
  4. chdir +($foo) * 20;# chdir ($foo * 20)
  5. rand 10 * 20;# rand (10 * 20)
  6. rand(10) * 20;# (rand 10) * 20
  7. rand (10) * 20;# (rand 10) * 20
  8. rand +(10) * 20;# rand (10 * 20)

Regarding precedence, the filetest operators, like -f, -M, etc. aretreated like named unary operators, but they don't follow this functionalparenthesis rule. That means, for example, that -f($file).".bak" isequivalent to -f "$file.bak".

See also Terms and List Operators (Leftward).

Relational Operators

Perl operators that return true or false generally return values that can be safely used as numbers. For example, the relationaloperators in this section and the equality operators in the nextone return 1 for true and a special version of the defined emptystring, "", which counts as a zero but is exempt from warningsabout improper numeric conversions, just as "0 but true" is.

Binary "<" returns true if the left argument is numerically less thanthe right argument.

Binary ">" returns true if the left argument is numerically greaterthan the right argument.

Binary "<=" returns true if the left argument is numerically less thanor equal to the right argument.

Binary ">=" returns true if the left argument is numerically greaterthan or equal to the right argument.

Binary "lt" returns true if the left argument is stringwise less thanthe right argument.

Binary "gt" returns true if the left argument is stringwise greaterthan the right argument.

Binary "le" returns true if the left argument is stringwise less thanor equal to the right argument.

Binary "ge" returns true if the left argument is stringwise greaterthan or equal to the right argument.

Equality Operators

Binary "==" returns true if the left argument is numerically equal tothe right argument.

Binary "!=" returns true if the left argument is numerically not equalto the right argument.

Binary "<=>" returns -1, 0, or 1 depending on whether the leftargument is numerically less than, equal to, or greater than the rightargument. If your platform supports NaNs (not-a-numbers) as numericvalues, using them with "<=>" returns undef. NaN is not "<", "==", ">","<=" or ">=" anything (even NaN), so those 5 return false. NaN != NaNreturns true, as does NaN != anything else. If your platform doesn'tsupport NaNs then NaN is just a string with numeric value 0.

  1. $ perl -le '$a = "NaN" print "No NaN support here" if $a == $a'
  2. $ perl -le '$a = "NaN" print "NaN support here" if $a != $a'

(Note that the bigint, bigrat, and bignum pragmas all support "NaN".)

Binary "eq" returns true if the left argument is stringwise equal tothe right argument.

Binary "ne" returns true if the left argument is stringwise not equalto the right argument.

Binary "cmp" returns -1, 0, or 1 depending on whether the leftargument is stringwise less than, equal to, or greater than the rightargument.

Binary "~~" does a smartmatch between its arguments. Smart matchingis described in the next section.

"lt", "le", "ge", "gt" and "cmp" use the collation (sort) order specifiedby the current locale if a legacy use locale (but notuse locale ':not_characters') is in effect. Seeperllocale. Do not mix these with Unicode, only with legacy binaryencodings. The standard Unicode::Collate andUnicode::Collate::Locale modules offer much more powerful solutions tocollation issues.

Smartmatch Operator

First available in Perl 5.10.1 (the 5.10.0 version behaved differently),binary ~~ does a "smartmatch" between its arguments. This is mostlyused implicitly in the when construct described in perlsyn, althoughnot all when clauses call the smartmatch operator. Unique among all ofPerl's operators, the smartmatch operator can recurse.

It is also unique in that all other Perl operators impose a context(usually string or numeric context) on their operands, autoconvertingthose operands to those imposed contexts. In contrast, smartmatchinfers contexts from the actual types of its operands and uses thattype information to select a suitable comparison mechanism.

The ~~ operator compares its operands "polymorphically", determining howto compare them according to their actual types (numeric, string, array,hash, etc.) Like the equality operators with which it shares the sameprecedence, ~~ returns 1 for true and "" for false. It is often bestread aloud as "in", "inside of", or "is contained in", because the leftoperand is often looked for inside the right operand. That makes theorder of the operands to the smartmatch operand often opposite that ofthe regular match operator. In other words, the "smaller" thing is usuallyplaced in the left operand and the larger one in the right.

The behavior of a smartmatch depends on what type of things its argumentsare, as determined by the following table. The first row of the tablewhose types apply determines the smartmatch behavior. Because whatactually happens is mostly determined by the type of the second operand,the table is sorted on the right operand instead of on the left.

  1. Left Right Description and pseudocode
  2. ===============================================================
  3. Any undef check whether Any is undefined
  4. like: !defined Any
  5. Any Object invoke ~~ overloading on Object, or die
  6. Right operand is an ARRAY:
  7. Left Right Description and pseudocode
  8. ===============================================================
  9. ARRAY1 ARRAY2 recurse on paired elements of ARRAY1 and ARRAY2[2]
  10. like: (ARRAY1[0] ~~ ARRAY2[0])
  11. && (ARRAY1[1] ~~ ARRAY2[1]) && ...
  12. HASH ARRAY any ARRAY elements exist as HASH keys
  13. like: grep { exists HASH->{$_} } ARRAY
  14. Regexp ARRAY any ARRAY elements pattern match Regexp
  15. like: grep { /Regexp/ } ARRAY
  16. undef ARRAY undef in ARRAY
  17. like: grep { !defined } ARRAY
  18. Any ARRAY smartmatch each ARRAY element[3]
  19. like: grep { Any ~~ $_ } ARRAY
  20. Right operand is a HASH:
  21. Left Right Description and pseudocode
  22. ===============================================================
  23. HASH1 HASH2 all same keys in both HASHes
  24. like: keys HASH1 ==
  25. grep { exists HASH2->{$_} } keys HASH1
  26. ARRAY HASH any ARRAY elements exist as HASH keys
  27. like: grep { exists HASH->{$_} } ARRAY
  28. Regexp HASH any HASH keys pattern match Regexp
  29. like: grep { /Regexp/ } keys HASH
  30. undef HASH always false (undef can't be a key)
  31. like: 0 == 1
  32. Any HASH HASH key existence
  33. like: exists HASH->{Any}
  34. Right operand is CODE:
  35. Left Right Description and pseudocode
  36. ===============================================================
  37. ARRAY CODE sub returns true on all ARRAY elements[1]
  38. like: !grep { !CODE->($_) } ARRAY
  39. HASH CODE sub returns true on all HASH keys[1]
  40. like: !grep { !CODE->($_) } keys HASH
  41. Any CODE sub passed Any returns true
  42. like: CODE->(Any)

Right operand is a Regexp:

  1. Left Right Description and pseudocode
  2. ===============================================================
  3. ARRAY Regexp any ARRAY elements match Regexp
  4. like: grep { /Regexp/ } ARRAY
  5. HASH Regexp any HASH keys match Regexp
  6. like: grep { /Regexp/ } keys HASH
  7. Any Regexp pattern match
  8. like: Any =~ /Regexp/
  9. Other:
  10. Left Right Description and pseudocode
  11. ===============================================================
  12. Object Any invoke ~~ overloading on Object,
  13. or fall back to...
  14. Any Num numeric equality
  15. like: Any == Num
  16. Num nummy[4] numeric equality
  17. like: Num == nummy
  18. undef Any check whether undefined
  19. like: !defined(Any)
  20. Any Any string equality
  21. like: Any eq Any

Notes:

1.
Empty hashes or arrays match.
2.
That is, each element smartmatches the element of the same index in the other array.[3]
3.
If a circular reference is found, fall back to referential equality.
4.
Either an actual number, or a string that looks like one.

The smartmatch implicitly dereferences any non-blessed hash or arrayreference, so the HASH and ARRAY entries apply in those cases.For blessed references, the Object entries apply. Smartmatchesinvolving hashes only consider hash keys, never hash values.

The "like" code entry is not always an exact rendition. For example, thesmartmatch operator short-circuits whenever possible, but grep doesnot. Also, grep in scalar context returns the number of matches, but~~ returns only true or false.

Unlike most operators, the smartmatch operator knows to treat undefspecially:

  1. use v5.10.1;
  2. @array = (1, 2, 3, undef, 4, 5);
  3. say "some elements undefined" if undef ~~ @array;

Each operand is considered in a modified scalar context, the modificationbeing that array and hash variables are passed by reference to theoperator, which implicitly dereferences them. Both elementsof each pair are the same:

  1. use v5.10.1;
  2. my %hash = (red => 1, blue => 2, green => 3,
  3. orange => 4, yellow => 5, purple => 6,
  4. black => 7, grey => 8, white => 9);
  5. my @array = qw(red blue green);
  6. say "some array elements in hash keys" if @array ~~ %hash;
  7. say "some array elements in hash keys" if \@array ~~ \%hash;
  8. say "red in array" if "red" ~~ @array;
  9. say "red in array" if "red" ~~ \@array;
  10. say "some keys end in e" if /e$/ ~~ %hash;
  11. say "some keys end in e" if /e$/ ~~ \%hash;

Two arrays smartmatch if each element in the first array smartmatches(that is, is "in") the corresponding element in the second array,recursively.

  1. use v5.10.1;
  2. my @little = qw(red blue green);
  3. my @bigger = ("red", "blue", [ "orange", "green" ] );
  4. if (@little ~~ @bigger) { # true!
  5. say "little is contained in bigger";
  6. }

Because the smartmatch operator recurses on nested arrays, thiswill still report that "red" is in the array.

  1. use v5.10.1;
  2. my @array = qw(red blue green);
  3. my $nested_array = [[[[[[[ @array ]]]]]]];
  4. say "red in array" if "red" ~~ $nested_array;

If two arrays smartmatch each other, then they are deepcopies of each others' values, as this example reports:

  1. use v5.12.0;
  2. my @a = (0, 1, 2, [3, [4, 5], 6], 7);
  3. my @b = (0, 1, 2, [3, [4, 5], 6], 7);
  4. if (@a ~~ @b && @b ~~ @a) {
  5. say "a and b are deep copies of each other";
  6. }
  7. elsif (@a ~~ @b) {
  8. say "a smartmatches in b";
  9. }
  10. elsif (@b ~~ @a) {
  11. say "b smartmatches in a";
  12. }
  13. else {
  14. say "a and b don't smartmatch each other at all";
  15. }

If you were to set $b[3] = 4, then instead of reporting that "a and bare deep copies of each other", it now reports that "b smartmatches in a".That because the corresponding position in @a contains an array that(eventually) has a 4 in it.

Smartmatching one hash against another reports whether both contain thesame keys, no more and no less. This could be used to see whether tworecords have the same field names, without caring what values those fieldsmight have. For example:

  1. use v5.10.1;
  2. sub make_dogtag {
  3. state $REQUIRED_FIELDS = { name=>1, rank=>1, serial_num=>1 };
  4. my ($class, $init_fields) = @_;
  5. die "Must supply (only) name, rank, and serial number"
  6. unless $init_fields ~~ $REQUIRED_FIELDS;
  7. ...
  8. }

or, if other non-required fields are allowed, use ARRAY ~~ HASH:

  1. use v5.10.1;
  2. sub make_dogtag {
  3. state $REQUIRED_FIELDS = { name=>1, rank=>1, serial_num=>1 };
  4. my ($class, $init_fields) = @_;
  5. die "Must supply (at least) name, rank, and serial number"
  6. unless [keys %{$init_fields}] ~~ $REQUIRED_FIELDS;
  7. ...
  8. }

The smartmatch operator is most often used as the implicit operator of awhen clause. See the section on "Switch Statements" in perlsyn.

Smartmatching of Objects

To avoid relying on an object's underlying representation, if thesmartmatch's right operand is an object that doesn't overload ~~,it raises the exception "Smartmatching a non-overloaded objectbreaks encapsulation". That's because one has no business diggingaround to see whether something is "in" an object. These are allillegal on objects without a ~~ overload:

  1. %hash ~~ $object
  2. 42 ~~ $object
  3. "fred" ~~ $object

However, you can change the way an object is smartmatched by overloadingthe ~~ operator. This is allowed to extend the usual smartmatch semantics.For objects that do have an ~~ overload, see overload.

Using an object as the left operand is allowed, although not very useful.Smartmatching rules take precedence over overloading, so even if theobject in the left operand has smartmatch overloading, this will beignored. A left operand that is a non-overloaded object falls back on astring or numeric comparison of whatever the ref operator returns. Thatmeans that

  1. $object ~~ X

does not invoke the overload method with X as an argument.Instead the above table is consulted as normal, and based on the type ofX, overloading may or may not be invoked. For simple strings ornumbers, in becomes equivalent to this:

  1. $object ~~ $number ref($object) == $number
  2. $object ~~ $string ref($object) eq $string

For example, this reports that the handle smells IOish(but please don't really do this!):

  1. use IO::Handle;
  2. my $fh = IO::Handle->new();
  3. if ($fh ~~ /\bIO\b/) {
  4. say "handle smells IOish";
  5. }

That's because it treats $fh as a string like"IO::Handle=GLOB(0x8039e0)", then pattern matches against that.

Bitwise And

Binary "&" returns its operands ANDed together bit by bit.(See also Integer Arithmetic and Bitwise String Operators.)

Note that "&" has lower priority than relational operators, so for examplethe parentheses are essential in a test like

  1. print "Even\n" if ($x & 1) == 0;

Bitwise Or and Exclusive Or

Binary "|" returns its operands ORed together bit by bit.(See also Integer Arithmetic and Bitwise String Operators.)

Binary "^" returns its operands XORed together bit by bit.(See also Integer Arithmetic and Bitwise String Operators.)

Note that "|" and "^" have lower priority than relational operators, sofor example the brackets are essential in a test like

  1. print "false\n" if (8 | 2) != 10;

C-style Logical And

Binary "&&" performs a short-circuit logical AND operation. That is,if the left operand is false, the right operand is not even evaluated.Scalar or list context propagates down to the right operand if itis evaluated.

C-style Logical Or

Binary "||" performs a short-circuit logical OR operation. That is,if the left operand is true, the right operand is not even evaluated.Scalar or list context propagates down to the right operand if itis evaluated.

Logical Defined-Or

Although it has no direct equivalent in C, Perl's // operator is relatedto its C-style or. In fact, it's exactly the same as ||, except that ittests the left hand side's definedness instead of its truth. Thus,EXPR1 // EXPR2 returns the value of EXPR1 if it's defined,otherwise, the value of EXPR2 is returned. (EXPR1 is evaluatedin scalar context, EXPR2 in the context of // itself). Usually,this is the same result as defined(EXPR1) ? EXPR1 : EXPR2 (except thatthe ternary-operator form can be used as a lvalue, while EXPR1 // EXPR2cannot). This is very useful forproviding default values for variables. If you actually want to test ifat least one of $a and $b is defined, use defined($a // $b).

The ||, // and && operators return the last value evaluated(unlike C's || and &&, which return 0 or 1). Thus, a reasonablyportable way to find out the home directory might be:

  1. $home = $ENV{HOME}
  2. // $ENV{LOGDIR}
  3. // (getpwuid($<))[7]
  4. // die "You're homeless!\n";

In particular, this means that you shouldn't use thisfor selecting between two aggregates for assignment:

  1. @a = @b || @c;# this is wrong
  2. @a = scalar(@b) || @c;# really meant this
  3. @a = @b ? @b : @c;# this works fine, though

As alternatives to && and || when used forcontrol flow, Perl provides the and and or operators (see below).The short-circuit behavior is identical. The precedence of "and"and "or" is much lower, however, so that you can safely use them after alist operator without the need for parentheses:

  1. unlink "alpha", "beta", "gamma"
  2. or gripe(), next LINE;

With the C-style operators that would have been written like this:

  1. unlink("alpha", "beta", "gamma")
  2. || (gripe(), next LINE);

It would be even more readable to write that this way:

  1. unless(unlink("alpha", "beta", "gamma")) {
  2. gripe();
  3. next LINE;
  4. }

Using "or" for assignment is unlikely to do what you want; see below.

Range Operators

Binary ".." is the range operator, which is really two differentoperators depending on the context. In list context, it returns alist of values counting (up by ones) from the left value to the rightvalue. If the left value is greater than the right value then itreturns the empty list. The range operator is useful for writingforeach (1..10) loops and for doing slice operations on arrays. Inthe current implementation, no temporary array is created when therange operator is used as the expression in foreach loops, but olderversions of Perl might burn a lot of memory when you write somethinglike this:

  1. for (1 .. 1_000_000) {
  2. # code
  3. }

The range operator also works on strings, using the magicalauto-increment, see below.

In scalar context, ".." returns a boolean value. The operator isbistable, like a flip-flop, and emulates the line-range (comma)operator of sed, awk, and various editors. Each ".." operatormaintains its own boolean state, even across calls to a subroutinethat contains it. It is false as long as its left operand is false.Once the left operand is true, the range operator stays true until theright operand is true, AFTER which the range operator becomes falseagain. It doesn't become false till the next time the range operatoris evaluated. It can test the right operand and become false on thesame evaluation it became true (as in awk), but it still returnstrue once. If you don't want it to test the right operand until thenext evaluation, as in sed, just use three dots ("...") instead oftwo. In all other regards, "..." behaves just like ".." does.

The right operand is not evaluated while the operator is in the"false" state, and the left operand is not evaluated while theoperator is in the "true" state. The precedence is a little lowerthan || and &&. The value returned is either the empty string forfalse, or a sequence number (beginning with 1) for true. The sequencenumber is reset for each range encountered. The final sequence numberin a range has the string "E0" appended to it, which doesn't affectits numeric value, but gives you something to search for if you wantto exclude the endpoint. You can exclude the beginning point bywaiting for the sequence number to be greater than 1.

If either operand of scalar ".." is a constant expression,that operand is considered true if it is equal (==) to the currentinput line number (the $. variable).

To be pedantic, the comparison is actually int(EXPR) == int(EXPR),but that is only an issue if you use a floating point expression; whenimplicitly using $. as described in the previous paragraph, thecomparison is int(EXPR) == int($.) which is only an issue when $.is set to a floating point value and you are not reading from a file.Furthermore, "span" .. "spat" or 2.18 .. 3.14 will not do whatyou want in scalar context because each of the operands are evaluatedusing their integer representation.

Examples:

As a scalar operator:

  1. if (101 .. 200) { print; } # print 2nd hundred lines, short for
  2. # if ($. == 101 .. $. == 200) { print; }
  3. next LINE if (1 .. /^$/); # skip header lines, short for
  4. # next LINE if ($. == 1 .. /^$/);
  5. # (typically in a loop labeled LINE)
  6. s/^/> / if (/^$/ .. eof()); # quote body
  7. # parse mail messages
  8. while (<>) {
  9. $in_header = 1 .. /^$/;
  10. $in_body = /^$/ .. eof;
  11. if ($in_header) {
  12. # do something
  13. } else { # in body
  14. # do something else
  15. }
  16. } continue {
  17. close ARGV if eof; # reset $. each file
  18. }

Here's a simple example to illustrate the difference betweenthe two range operators:

  1. @lines = (" - Foo",
  2. "01 - Bar",
  3. "1 - Baz",
  4. " - Quux");
  5. foreach (@lines) {
  6. if (/0/ .. /1/) {
  7. print "$_\n";
  8. }
  9. }

This program will print only the line containing "Bar". Ifthe range operator is changed to ..., it will also print the"Baz" line.

And now some examples as a list operator:

  1. for (101 .. 200) { print } # print $_ 100 times
  2. @foo = @foo[0 .. $#foo]; # an expensive no-op
  3. @foo = @foo[$#foo-4 .. $#foo]; # slice last 5 items

The range operator (in list context) makes use of the magicalauto-increment algorithm if the operands are strings. Youcan say

  1. @alphabet = ("A" .. "Z");

to get all normal letters of the English alphabet, or

  1. $hexdigit = (0 .. 9, "a" .. "f")[$num & 15];

to get a hexadecimal digit, or

  1. @z2 = ("01" .. "31");
  2. print $z2[$mday];

to get dates with leading zeros.

If the final value specified is not in the sequence that the magicalincrement would produce, the sequence goes until the next value wouldbe longer than the final value specified.

If the initial value specified isn't part of a magical incrementsequence (that is, a non-empty string matching /^[a-zA-Z]*[0-9]*\z/),only the initial value will be returned. So the following will onlyreturn an alpha:

  1. use charnames "greek";
  2. my @greek_small = ("\N{alpha}" .. "\N{omega}");

To get the 25 traditional lowercase Greek letters, including both sigmas,you could use this instead:

  1. use charnames "greek";
  2. my @greek_small = map { chr } ( ord("\N{alpha}")
  3. ..
  4. ord("\N{omega}")
  5. );

However, because there are many other lowercase Greek characters thanjust those, to match lowercase Greek characters in a regular expression,you would use the pattern /(?:(?=\p{Greek})\p{Lower})+/.

Because each operand is evaluated in integer form, 2.18 .. 3.14 willreturn two elements in list context.

  1. @list = (2.18 .. 3.14); # same as @list = (2 .. 3);

Conditional Operator

Ternary "?:" is the conditional operator, just as in C. It works muchlike an if-then-else. If the argument before the ? is true, theargument before the : is returned, otherwise the argument after the :is returned. For example:

  1. printf "I have %d dog%s.\n", $n,
  2. ($n == 1) ? "" : "s";

Scalar or list context propagates downward into the 2ndor 3rd argument, whichever is selected.

  1. $a = $ok ? $b : $c; # get a scalar
  2. @a = $ok ? @b : @c; # get an array
  3. $a = $ok ? @b : @c; # oops, that's just a count!

The operator may be assigned to if both the 2nd and 3rd arguments arelegal lvalues (meaning that you can assign to them):

  1. ($a_or_b ? $a : $b) = $c;

Because this operator produces an assignable result, using assignmentswithout parentheses will get you in trouble. For example, this:

  1. $a % 2 ? $a += 10 : $a += 2

Really means this:

  1. (($a % 2) ? ($a += 10) : $a) += 2

Rather than this:

  1. ($a % 2) ? ($a += 10) : ($a += 2)

That should probably be written more simply as:

  1. $a += ($a % 2) ? 10 : 2;
Source : perldoc.perl.org - Official documentation for the Perl programming language
Site maintained by Jon Allen (JJ)     See the project page for more details
Documentation maintained by the Perl 5 Porters
(Sebelumnya) Daftar IsiAssignment Operators (Berikutnya)