1#!/usr/bin/perl -w 2 3use strict; 4use warnings; 5 6use Test::More; 7 8{ 9 package Stuff; 10 11 use Test::More; 12 use Method::Signatures; 13 14 method add($this = 23, $that = 42) { 15 return $this + $that; 16 } 17 18 method minus($this is ro = 23, $that is ro = 42) { 19 return $this - $that; 20 } 21 22 is( Stuff->add(), 23 + 42 ); 23 is( Stuff->add(99), 99 + 42 ); 24 is( Stuff->add(2,3), 5 ); 25 26 is( Stuff->minus(), 23 - 42 ); 27 is( Stuff->minus(99), 99 - 42 ); 28 is( Stuff->minus(2, 3), 2 - 3 ); 29 30 31 # Test that undef overrides defaults 32 method echo($message = "what?") { 33 return $message 34 } 35 36 is( Stuff->echo(), "what?" ); 37 is( Stuff->echo(undef), undef ); 38 is( Stuff->echo("who?"), 'who?' ); 39 40 41 # Test that you can reference earlier args in a default 42 method copy_cat($this, $that = $this) { 43 return $that; 44 } 45 46 is( Stuff->copy_cat("wibble"), "wibble" ); 47 is( Stuff->copy_cat(23, 42), 42 ); 48} 49 50 51{ 52 package Bar; 53 use Test::More; 54 use Method::Signatures; 55 56 method hello($msg = "Hello, world!") { 57 return $msg; 58 } 59 60 is( Bar->hello, "Hello, world!" ); 61 is( Bar->hello("Greetings!"), "Greetings!" ); 62 63 64 method hi($msg = q,Hi,) { 65 return $msg; 66 } 67 68 is( Bar->hi, "Hi" ); 69 is( Bar->hi("Yo"), "Yo" ); 70 71 72 method list(@args = (1,2,3)) { 73 return @args; 74 } 75 76 is_deeply [Bar->list()], [1,2,3]; 77 78 79 method code($num, $code = sub { $num + 2 }) { 80 return $code->(); 81 } 82 83 is( Bar->code(42), 44 ); 84} 85 86note "Defaults are type checked"; { 87 package Biff; 88 use Test::More; 89 use Method::Signatures; 90 91 func hi( 92 Object $place = "World" 93 ) { 94 return "Hi, $place!\n"; 95 } 96 97 ok !eval { hi() }; 98 like $@, qr/the 'place' parameter \("World"\) is not of type Object/; 99} 100 101 102note "Multi-line defaults"; { 103 package Whatever; 104 105 use Method::Signatures; 106 use Test::More; 107 108 func stuff( 109 $arg = { 110 foo => 23, 111 bar => 42 112 } 113 ) { 114 return $arg->{foo}; 115 } 116 117 is( stuff(), 23 ); 118 119 func things( 120 $arg = "Hello 121There" 122 ) { 123 return $arg; 124 } 125 126 is( things(), "Hello\nThere" ); 127} 128 129done_testing; 130