Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I think you really want <code>allowed_values</code> to be a separate data structure with the efficiency and ordering properties you desire. Since it doesn't look like you care about the ordering, why not:</p> <pre><code>has 'allowed_values' =&gt; ( traits =&gt; ['Hash'], isa =&gt; HashRef[Bool], default =&gt; sub { +{} }, handles =&gt; { _add_allowed_value =&gt; 'set', remove_allowed_value =&gt; 'delete', value_is_allowed =&gt; 'exists', allowed_values =&gt; 'keys', }, ); method add_allowed_value(Str $value){ $self-&gt;_add_allowed_value( $value, 1 ); } </code></pre> <p>In general, anything not specific to the class being implemented should probably be implemented elsewhere. Making arrays have faster lookup times is not really the job of whatever class you are writing, so it should be implemented elsewhere, and this class should use that class. (In the simple case, like the hash above, maybe it's OK to ignore this rule. But if it were any more complicated, you would definitely want to factor it out.)</p> <p>Edit:</p> <p>If you want the user to think this is a list, how about:</p> <pre><code>use MooseX::Types::Moose qw(Bool ArrayRef HashRef); use MooseX::Types -declare =&gt; ['ListHash']; subtype ListHash, as HashRef[Bool]; coerce ListHash, from ArrayRef, via { +{ map { $_ =&gt; 1 } @$_ } }; has 'allowed_values' =&gt; ( # &lt;same as above&gt; isa =&gt; ListHash, writer =&gt; 'set_allowed_values', coerce =&gt; 1, ); </code></pre> <p>Now you can set <code>allowed_values</code> like:</p> <pre><code>my $instance = Class-&gt;new( allowed_values =&gt; [qw/foo bar/] ); $instance-&gt;set_allowed_values([qw/foo bar baz/]); </code></pre> <p>And access them like:</p> <pre><code>my @allowed_values = $instance-&gt;allowed_values; ... if $instance-&gt;value_is_allowed('foo'); </code></pre> <p>And modify them:</p> <pre><code>$instance-&gt;remove_allowed_value('foo'); $instance-&gt;add_allowed_value('gorch'); </code></pre> <p>This hides any underlying implementation details from the user.</p> <p>BTW, is building the hash actually and using it significantly faster than a linear scan over 3 elements?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload