Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP

Loading…

Adding as_hash method #214

Merged
merged 2 commits into from

3 participants

@qrazhan

Added the as_hash method for my Google Code-In task. Added method to ARRAY.pm, added as_hash.t to the t folder, and added documentation in perl5i.pm

@doherty

Should this explicitly use CORE::map like the rest of the methods here?

@schwern schwern merged commit fd036bc into evalEmpire:master
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Commits on Nov 23, 2011
  1. @qrazhan

    Adding as_hash method

    qrazhan authored
  2. @qrazhan
This page is out of date. Refresh to see the latest.
Showing with 34 additions and 0 deletions.
  1. +13 −0 lib/perl5i.pm
  2. +5 −0 lib/perl5i/2/ARRAY.pm
  3. +16 −0 t/as_hash.t
View
13 lib/perl5i.pm
@@ -620,6 +620,19 @@ A normal subroutine with no signature will get one at a time.
If @array is not a multiple of the iteration (for example, @array has
5 elements and you ask 2 at a time) the behavior is currently undefined.
+=head3 as_hash
+
+ %hash = @array->as_hash;
+
+This method returns an array with the original elements of @array mapped to 1.
+Its functionality is the exact same as:
+
+ %hash = map{ $_ => 1 } @array;
+
+Example usage:
+
+ my @array = ("a", "b", "c");
+ my %hash = @array->as_hash;
=head3 diff
View
5 lib/perl5i/2/ARRAY.pm
@@ -44,6 +44,11 @@ method map( $code ) {
return wantarray ? @result : \@result;
}
+method as_hash{
+ my @result = CORE::map{ $_ => 1 } @$self;
+ return wantarray ? @result : \@result;
+}
+
method grep($filter) {
my @result = CORE::grep { $_ ~~ $filter } @$self;
View
16 t/as_hash.t
@@ -0,0 +1,16 @@
+ #!/usr/bin/perl
+
+ use perl5i::latest;
+ use Test::More;
+
+ note 'array to hash'; {
+ my @array = qw(a b c);
+ my %hash = @array->as_hash;
+
+ is_deeply \%hash, {a=>1, b=>1, c=>1};
+ @array = (4, 3, 2, 1);
+ %hash = @array->as_hash;
+ is_deeply \%hash, {4=>1, 3=>1, 2=>1, 1=>1};
+}
+
+ done_testing(2);
Something went wrong with that request. Please try again.