This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Optimise 'if ($a || $b)' and 'unless ($a && $b)' early exit
[perl5.git] / t / op / or.t
CommitLineData
1a28061a
MS
1#!./perl
2
3# Test || in weird situations.
4
5BEGIN {
6 chdir 't' if -d 't';
7 @INC = '../lib';
8}
9
10
11package Countdown;
12
13sub TIESCALAR {
14 my $class = shift;
15 my $instance = shift || undef;
16 return bless \$instance => $class;
17}
18
19sub FETCH {
20 print "# FETCH! ${$_[0]}\n";
21 return ${$_[0]}--;
22}
23
24
25package main;
26require './test.pl';
27
e45d8982 28plan( tests => 11 );
1a28061a
MS
29
30
31my ($a, $b, $c);
32
33$! = 1;
34$a = $!;
35my $a_str = sprintf "%s", $a;
36my $a_num = sprintf "%d", $a;
37
38$c = $a || $b;
39
236d1a76
JK
40is($c, $a_str, "comparison of string equality");
41is($c+0, $a_num, "comparison of numeric equality"); # force numeric context.
1a28061a
MS
42
43$a =~ /./g or die "Match failed for some reason"; # Make $a magic
44
45$c = $a || $b;
46
236d1a76
JK
47is($c, $a_str, "comparison of string equality");
48is($c+0, $a_num, "comparison of numeric equality"); # force numeric context.
1a28061a
MS
49
50my $val = 3;
51
52$c = $val || $b;
236d1a76 53is($c, 3, "|| short-circuited as expected");
1a28061a
MS
54
55tie $a, 'Countdown', $val;
56
57$c = $a;
58is($c, 3, 'Single FETCH on tied scalar');
59
60$c = $a;
61is($c, 2, ' $tied = $var');
62
63$c = $a || $b;
64
65{
66 local $TODO = 'Double FETCH';
67 is($c, 1, ' $tied || $var');
68}
2e73d70e
FC
69
70$y = " ";
71for (pos $x || pos $y) {
72 eval { $_++ };
73}
74is(pos($y) || $@, 1, "|| propagates lvaluish context");
e45d8982
MH
75
76my $aa, $bb, $cc;
77$bb = 1;
78
79my $res = 0;
80# Well, really testing OP_DOR I guess
81unless ($aa || $bb // $cc) {
82 $res = 1;
83}
84is($res, 0, "res is 0 after mixed OR/DOR");
85
86$res = 0;
87unless ($aa // $bb || $cc) {
88 $res = 1;
89}
90is($res, 0, "res is 0 after mixed DOR/OR");