Create an object/Native demonstration: Difference between revisions

Content added Content deleted
Line 292: Line 292:
eval {...} called at test.pl line 66</lang>
eval {...} called at test.pl line 66</lang>
=={{header|Perl 6}}==
=={{header|Perl 6}}==
{{works with|rakudo|2013-02-22}}
{{works with|rakudo|2015.10-29}}
Here we use delegation to handle all the normal hash methods that we don't need to override to define our new class.
Here we use delegation to handle all the normal hash methods that we don't need to override to define our new class.
<lang perl6>class FixedHash {
<lang perl6>class FixedHash {
has $.hash handles *;
has $.hash handles *;
method new(*@args) { self.bless: *, hash => Hash.new: @args }
method new(*@args) { self.bless: *, hash => Hash.new: @args }
method at_key(FixedHash:D: $key is copy) is rw {
method AT-KEY(FixedHash:D: $key is copy) is rw {
$!hash.exists($key) ?? $!hash.at_key($key) !! Nil;
$!hash.EXISTS-KEY($key) ?? $!hash.AT-KEY($key) !! Failure.new(q{can't store value for unknown key});
}
}
method delete($key) { $!hash.{$key} = Nil }
method DELETE-KEY($key) { $!hash.{$key} = Nil }
}
}


Line 311: Line 311:
say $fh<a b>; # 1 42
say $fh<a b>; # 1 42
say $fh<c>; # Nil
say $fh<c>; # Nil
$fh<c> = 43; # error</lang>
$fh<c> = 43; # error
</lang>
{{out}}
{{out}}
<pre>1 2
<pre>(1 2)
1 Nil
(1 (Any))
1 42
(1 42)
can't store value for unknown key
Nil
in block <unit> at native-demonstration.p6:17
Cannot assign to a non-container

in block at freezehash:21</pre>
Actually thrown at:
in block <unit> at native-demonstration.p6:17</pre>


=={{header|Python}}==
=={{header|Python}}==