Created
December 14, 2012 19:54
-
-
Save jacoby/4288130 to your computer and use it in GitHub Desktop.
I got complex data structures working with Redis and Perl. If you can't store complex data structures, why even deal with Redis?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/perl | |
| # http://search.cpan.org/~dpavlin/Redis-0.0801/lib/Redis.pm | |
| use 5.010 ; | |
| use strict ; | |
| use warnings ; | |
| use Data::Dumper ; | |
| use Redis ; | |
| { | |
| # Using the data | |
| my @fields = qw{ firstname lastname email building office username } ; | |
| my $r = Redis->new() ; | |
| my $u = 'users' ; | |
| my @users = $r->lrange( $u , 0 , $r->llen( $u ) ) ; | |
| for my $user ( sort @users ) { | |
| my @user_data = $r->hmget( 'user:'.$user , @fields ) ; | |
| my %user_data = map { | |
| $fields[ $_ ] => $user_data[ $_ ] | |
| } 0 .. scalar @fields - 1; | |
| say Dumper \%user_data ; | |
| } | |
| $r->quit ; | |
| } | |
| exit ; | |
| { | |
| # Setting the data | |
| my $data = { | |
| 'bobama' => { | |
| email => 'obama@whitehouse.gov', | |
| firstname => 'Barack', | |
| lastname => 'Obama', | |
| office => 'Oval', | |
| building => 'White House', | |
| title => 'President of the United States' , | |
| }, | |
| 'jboehner' => { | |
| email => 'boehnerj@house.gov', | |
| firstname => 'John', | |
| lastname => 'Boehner', | |
| office => '1011', | |
| building => 'Longworth House', | |
| title => 'Speaker of the House' , | |
| }, | |
| 'hreid' => { | |
| email => 'hreid@senate.gov', | |
| firstname => 'Harry', | |
| lastname => 'Reid', | |
| office => '522', | |
| building => 'Hart Senate Office Building', | |
| title => 'Senate Majority Leader' , | |
| }, | |
| } ; | |
| my $r = Redis->new() ; | |
| for my $u ( keys %$data ) { | |
| my $d = $data->{ $u } ; | |
| $r->lpush( 'users' , $u ) ; | |
| $r->hmset( | |
| 'user:' . $u => username => $u, | |
| firstname => $d->{ firstname }, | |
| lastname => $d->{ lastname }, | |
| email => $d->{ email }, | |
| building => $d->{ building }, | |
| office => $d->{ office }, | |
| ) ; | |
| } | |
| $r->quit ; | |
| } | |
| exit ; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment