open(FILE "## sub insertQuarter { my ($coin) = @_; (defined($coin) && $coin == 25) || die "You must insert 25 cents"; initializeGame(); startGame(); } #### # just return a false value and allow the # calling code to deal with the false return (defined($coin) && $coin == 25) || return 0; # warn the user of the wrong input and return # false, leaving the calling routine dealing # with things (defined($coin) && $coin == 25) || (warn("You must insert 25 cents"), return 0); # use a custom error handler which can record # call stack information, set error variable, # and return a specific value. (defined($coin) && $coin == 25) || return errorHandler("You must insert 25 cents"); #### #!/usr/bin/perl use strict; use warnings; use Benchmark qw(:all); sub IfBlocks { my ($test) = @_; if ($test < 50) { die "Test is wrong"; } return $test; } sub UnlessBlocks { my ($test) = @_; unless ($test > 50) { die "Test is wrong"; } return $test; } sub IfStatement { my ($test) = @_; die "Test is wrong" if ($test < 50); return $test; } sub UnlessStatement { my ($test) = @_; die "Test is wrong" unless ($test > 50); return $test; } sub Assert { my ($test) = @_; ($test < 50) || die "Test is wrong"; return $test; } sub Assert2 { my ($test) = @_; ($test > 50) && die "Test is wrong"; return $test; } my @nums = map { ((rand() * 100) % 50) } (0 .. 50); cmpthese(10000, { 'IfBlocks' => sub { eval { IfBlocks($_) } for (@nums) }, 'UnlessBlocks' => sub { eval { UnlessBlocks($_) } for (@nums) }, 'IfStatement' => sub { eval { IfStatement($_) } for (@nums) }, 'UnlessStatement' => sub { eval { UnlessStatement($_) } for (@nums) }, 'Assert' => sub { eval { Assert($_) } for (@nums) }, 'Assert2' => sub { eval { Assert2($_) } for (@nums) }, }); #### Benchmark: timing 10000 iterations of Assert, Assert2, IfBlocks, IfStatement, UnlessBlocks, UnlessStatement... Assert: 4 wallclock secs ( 2.38 usr + 0.02 sys = 2.40 CPU) @ 4166.67/s (n=10000) Assert2: 4 wallclock secs ( 2.36 usr + 0.03 sys = 2.39 CPU) @ 4184.10/s (n=10000) IfBlocks: 13 wallclock secs ( 7.82 usr + 0.13 sys = 7.95 CPU) @ 1257.86/s (n=10000) IfStatement: 13 wallclock secs ( 7.69 usr + 0.01 sys = 7.70 CPU) @ 1298.70/s (n=10000) UnlessBlocks: 12 wallclock secs (10.68 usr + 0.80 sys = 11.48 CPU) @ 871.08/s (n=10000) UnlessStatement: 11 wallclock secs (11.67 usr + 0.05 sys = 11.72 CPU) @ 853.24/s (n=10000) Rate UnlessStatement UnlessBlocks IfBlocks IfStatement Assert Assert2 UnlessStatement 853/s -- -2% -32% -34% -80% -80% UnlessBlocks 871/s 2% -- -31% -33% -79% -79% IfBlocks 1258/s 47% 44% -- -3% -70% -70% IfStatement 1299/s 52% 49% 3% -- -69% -69% Assert 4167/s 388% 378% 231% 221% -- -0% Assert2 4184/s 390% 380% 233% 222% 0% -- #### sub onlyAcceptFooObjects { my ($foo) = @_; (defined($foo) && ref($foo) && $foo->isa("Foo")) || die "This method only accepts Foo objects"; # ... }