1Sub::Infix(3)         User Contributed Perl Documentation        Sub::Infix(3)
2
3
4

NAME

6       Sub::Infix - create a fake infix operator
7

SYNOPSIS

9          use Sub::Infix;
10
11          # Operator needs to be defined (or imported) at compile time.
12          BEGIN { *plus = infix { $_[0] + $_[1] } };
13
14          my $five = 2 |plus| 3;
15

DESCRIPTION

17       Sub::Infix creates fake infix operators using overloading. It doesn't
18       use source filters, or Devel::Declare, or any of that magic. (Though
19       Devel::Declare isn't magic enough to define infix operators anyway; I
20       know; I've tried.) It's pure Perl, has no non-core dependencies, and
21       runs on Perl 5.6.
22
23       The price you pay for its simplicity is that you cannot define an
24       operator that can be used like this:
25
26          my $five = 2 plus 3;
27
28       Instead, the operator needs to be wrapped with real Perl operators in
29       one of three ways:
30
31          my $five = 2 |plus| 3;
32          my $five = 2 /plus/ 3;
33          my $five = 2 <<plus>> 3;
34
35       The advantage of this is that it gives you three different levels of
36       operator precedence.
37
38       You can also call the function a slightly less weird way:
39
40          my $five = plus->(2, 3);
41
42   How does it work?
43       "2 |plus| 3" is parsed by perl as: "2 | ( &plus() | 3 )".
44
45       &plus() returns an object that overloads the "|" operator; let's call
46       that $obj.
47
48       The overloaded "$obj | 3" operation stashes 3 inside $obj noting that
49       the number is the right operand, and returns $obj.
50
51       Then "2 | $obj" is evaluated, stashing 2 inside $obj as the left
52       operand. At this point, the object notices that it has both operands,
53       and calls the coderef from the definition of the operator, passing it
54       both operands.
55

BUGS

57       Please report any bugs to
58       <http://rt.cpan.org/Dist/Display.html?Queue=Sub-Infix>.
59

SEE ALSO

61       <http://code.activestate.com/recipes/384122-infix-operators/>.
62

AUTHOR

64       Toby Inkster <tobyink@cpan.org>.
65
67       This software is copyright (c) 2013-2014 by Toby Inkster.
68
69       This is free software; you can redistribute it and/or modify it under
70       the same terms as the Perl 5 programming language system itself.
71

DISCLAIMER OF WARRANTIES

73       THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
74       WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
75       MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
76
77
78
79perl v5.38.0                      2023-07-21                     Sub::Infix(3)
Impressum