kobame
kobame

Reputation: 5856

Using ArrayRef for random array item in perl

The following example works as expected.

use 5.014;
use warnings;

package My::Items {
        use Moose;
        use Method::Signatures::Simple;

        has 'items' => ( is => 'rw', isa => 'ArrayRef[Str]',);

        method get_random {
                my @itm = @{$self->items};
                return undef unless( @itm );
                return $itm[ int(rand(@itm)) ];
        }
        __PACKAGE__->meta->make_immutable();
}

package main {
        my $items = My::Items->new(items => [qw(a b c d)]);
        say $items->get_random for(1..5);
}

The question is: How to rewrite the get_random method without using the helper array @itm.

Upvotes: 0

Views: 85

Answers (1)

mpapec
mpapec

Reputation: 50637

    method get_random {
            return unless @{$self->items};
            return $self->items->[ int(rand(@{$self->items})) ];
    }

or if you don't mind using references,

    method get_random {
            my $itm = $self->items;
            return unless @$itm;
            return $itm->[ int(rand(@$itm)) ];
    }

Upvotes: 2

Related Questions