Using Perl Redis::Client::Hash can't locate object method "TIEHASH" - perl

I am trying to use Redis::Client::Hash per the instructions, but keep getting
"Can't locate object method "TIEHASH" via package "Redis::Client::Hash" at ./redishasttest.pl line 8."
Here's the code:
#!/usr/bin/perl -w
use strict;
use Redis::Client;
my $client = Redis::Client->new;
tie( my %hash, "Redis::Client::Hash", key => 'hello', client => $client);
my #keys = keys %hash;
$hash{foo} = 42;
print 1 if exists $hash{foo};
Seems straightforward enough -- Perl version 5.10.1, Redis 2.6.14. I am thinking it's a Moose thing or something, as the module has a TIEHASH sub. Redis::Client::Hash is actually installed when you install Redis::Client, so everything there looks good. The same sort of thing happens with Redis::Client::String so can't TIESCALAR. Am I missing something?
After friedo's answer, the solution to check that a hash key is set in redis is:
#!/usr/bin/perl -w
use strict;
use Redis::Client;
use Redis::Client::Hash;
my $key = 'hello';
my $client = Redis::Client->new;
# first make sure hash with key exists
if ($client->type($key) ne "hash") {
print "$key not a hash\n";
$client->hmset($key, dummy => 1);
}
tie( my %hash, "Redis::Client::Hash", key => $key, client => $client);
print "KEY VALUE\n" if %hash > 0;
foreach my $k (keys %hash) {
print "$k $hash{$k}\n";
}
Thanks again for the nice group of modules!

Redis::Client doesn't load the tie modules directly, so you just have to use them first.
use strict;
use Redis::Client;
use Redis::Client::Hash; # <---- add this
my $client = Redis::Client->new;
# first create something
$client->hset( 'hello', some => 'thing' );
tie( my %hash, "Redis::Client::Hash", key => 'hello', client => $client);
my #keys = keys %hash;
$hash{foo} = 42;
print 1 if exists $hash{foo};
It looks like I need to clarify that in the docs. I can probably do a new release this weekend.

Related

How do you access Tie::IxHash keys?

Greetings I need to generate a xml document from a nested perl hash, keeping the order of the hash keys. I am trying out https://metacpan.org/pod/Tie::IxHash
for the keeping the keys in order part.
However I cannot figure out how to access the hash keys that Tie::IxHash creates, they dont behave like a hash key, hash ref key or an object.
In the sample code I create a Tie::IxHash and try to print the key Transmitter
Here is the sample code:
use strict;
use warnings;
use diagnostics;
use Scalar::Util;
use Data::Dumper;
use XML::Writer;
use Tie::IxHash;
use DateTime::Format::XSD;
my $time = time;
my $dt = DateTime->now;
my $timestamp = DateTime::Format::XSD->format_datetime($dt);
my $transmissionId = sprintf("%u",int(rand(100000000000000000000))). "E";
#sample data structure as hsah ref
# my $transmissionHeader = {
# TransmissionId => "$transmissionId",
# Timestamp => "$timestamp",
# Transmitter => {
# ETIN => '1232456789',
# SOME => '5555555555',
# }
# };
my $transmissionHeader = Tie::IxHash->new(
TransmissionId => "$transmissionId",
Timestamp => "$timestamp",
Transmitter => Tie::IxHash->new( #each nested hash a new object?
ETIN => '1232456789',
SOME => '5555555555',
),
);
print Dumper $transmissionHeader;
# tried all these no joy
print "$transmissionHeader{Transmitter} \n";
print "$transmissionHeader->{Transmitter} \n";
print "$transmissionHeader->Transmitter() \n";
You can use the Indices() method to get the index of the key, and then use the Values() method to get the value of that key:
my $idx = $transmissionHeader->Indices('Transmitter');
my $hash = $transmissionHeader->Values($idx);
print Dumper $hash;

How do I add a new Key,Value pair to a Hash in an array of hash in perl?

Hi I have a need to add a new key,value pair to the hash entries within an array of hashes.
Below is some sample code which does not work(simplified with only 1 array entry) The output of the print statement just contains the 1 entry.
my #AoH;
push #AoH, { TEST1 => 'testvalue' };
for my $hash (#AoH)
{
$hash{'TEST2'} = 'testvalue2';
print Dumper($hash);
}
What am I doing wrong?
Thank you.
This code looks a little strange so I am going to assume it was done like that for the purposes of showing it briefly here, but the main thing you need to do to fix your code is change:
$hash{'TEST2'} = 'testvalue2';
to:
$$hash{'TEST2'} = 'testvalue2';
or:
$hash->{'TEST2'} = 'testvalue2';
The extra '$' or '->' dereferences the hash reference '$hash'. Since neither is there, it treats $hash{'TEST2'} as a different variable: '%hash' (not '$hash') and assigns 'testvalue2' to that. You would have gotten a good error message:
Global symbol "%hash" requires explicit package name at - line XX
if you tried to run this code with:
use strict;
use warnings;
at the beginning... which you should always do, so do that every time from now on.
use strict;
use warnings;
use Data::Dumper;
my #AoH=();
my %data_source_hash=(
TEST1 => 'testvalue1',
TEST2 => 'testvalue2'
);
# adds whole hash as the array element
push #AoH,{ %data_source_hash };
print Dumper(#AoH);
#AoH=();
print "---------------------------\n";
# adds each hash $key, $value pair as an element
while ( my ($key, $value) = each %data_source_hash )
{
push #AoH, { $key => $value };
}
print Dumper(#AoH);
#AoH=();
print "---------------------------\n";
# adds extra hash entry to each array element
push #AoH, { TEST1 => 'testvalue' };
push #AoH, { TEST3 => 'testvalue3' };
foreach my $el (#AoH)
{
my $key = 'TEST2';
$$el{$key} = $data_source_hash{$key};
}
print Dumper(#AoH);

Reference found where even-sized list expected in Perl - Possible pass-by-reference error?

I have a Perl class/module that I created to display Bible verses. In it there is a hash that stores several verses, with the key being the book/chapter/verse and the value being the text. This hash is returned from the module.
I'm including the Bible class in a controller class, and that connection seems to work. The problem is I keep getting errors on executing. My IDE because I'm following a Lynda tutorial, is Eclipse with the EPIC plugin.
The error is:
Reference found where even-sized list expected at C:/Documents and Settings/nunya/eric.hepperle_codebase/lynda/lamp/perl5/Exercise Files/14 Modules/eh_bibleInspiration_controller.pl line 42.
Use of uninitialized value $value in concatenation (.) or string at C:/Documents and Settings/nunya/eric.hepperle_codebase/lynda/lamp/perl5/Exercise Files/14 Modules/eh_bibleInspiration_controller.pl line 45.
HASH(0x19ad454) =>
Here is the CONTROLLER class:
#!/usr/bin/perl
# eh_bibleInspiration_controller.pl by Eric Hepperle - 06/23/13
#
use strict;
use warnings;
use Data::Dumper;
use EHW_BibleInspiration;
main(#ARGV);
sub main
{
my $o = EHW_BibleInspiration->new; # instantiate new object.
my %bo_ref = $o->getBibleObj();
print "\$o is type: " . ref($o) . ".\n";
print "\%bo_ref is type: " . ref(\%bo_ref) . ".\n";
# exit;
$o->getVerseObj();
listHash(\%bo_ref);
message("Done.");
}
sub message
{
my $m = shift or return;
print("$m\n");
}
sub error
{
my $e = shift || 'unkown error';
print("$0: $e\n");
exit 0;
}
sub listHash
{
my %hash = #_;
foreach my $key (sort keys %hash) {
my $value = $hash{$key};
message("$key => $value\n");
}
}
Here is the class that returns the verses and has the method to pick a random verse:
# EHW_BibleInspiration.pm
# EHW_BibleInspiration.
#
package EHW_BibleInspiration;
use strict;
use warnings;
use IO::File;
use Data::Dumper;
our $VERSION = "0.1";
sub new
{
my $class = shift;
my $self = {};
bless($self, $class); # turns hash into object
return $self;
}
sub getVerseObj
{
my ($self) = #_;
print "My Bible Verse:\n";
my $verses = $self->getBibleObj();
# get random verse
#$knockknocks{(keys %knockknocks)[rand keys %knockknocks]};
# sub mysub {
# my $params = shift;
# my %paramhash = %$params;
# }
# my %verses = %{$verses};
# my $random_value = %verses{(keys %verses)[rand keys %verses]};
# print Dumper(%{$random_value});
}
sub getBibleObj
{
my ($self) = #_;
# create bible verse object (ESV)
my $bibleObj_ref = {
'john 3:16' => 'For God so loved the world,that he gave his only Son, that whoever believes in him should not perish but have eternal life.',
'matt 10:8' => 'Heal the sick, raise the dead, cleanse lepers, cast out demons. You received without paying; give without pay.',
'Luke 6:38' => 'Give, and it will be given to you. Good measure, pressed down, shaken together, running over, will be put into your lap. For with the measure you use it will be measured back to you.',
'John 16:24' => 'Until now you have asked nothing in my name. Ask, and you will receive, that your joy may be full.',
'Psalms 32:7' => 'You are a hiding place for me; you preserve me from trouble; you surround me with shouts of deliverance. Selah',
'Proverbs 3:5-6' => 'Trust in the LORD with all your heart, and do not lean on your own understanding. 6 In all your ways acknowledge him, and he will make straight your paths.',
'John 14:1' => 'Let not your hearts be troubled. Believe in God; believe also in me.'
};
my $out = "The BIBLE is awesome!\n";
return $bibleObj_ref;
}
1;
What am I doing wrong? I suspect it has something to do with hash vs hash reference, but I don't know how to fix it. My dereferencing attempts had failed miserably because I don't really know what I'm doing. I modeled my random getter off of something I saw on perlmonks. #$knockknocks{(keys %knockknocks)[rand keys %knockknocks]};
In the main, you have:
my %bo_ref = $o->getBibleObj();
but, in package EHW_BibleInspiration;, the method getBibleObj returns : return $bibleObj_ref;
You'd do, in the main : my $bo_ref = $o->getBibleObj();
and then call listHash($bo_ref);
Finaly, don't forget to change sub listHash to:
sub listHash
{
my ($hash) = #_;
foreach my $key (sort keys %{$hash}) {
my $value = $hash->{$key};
message("$key => $value\n");
}
}
In your main, you do
listHash(\%bo_ref);
This passes a hash reference to the sub. However, it tries to unpack its arguments like
my %hash = #_;
Oops, it wants a hash.
Either, we pass it a hash: listHash(%bo_ref). This saves us much typing.
Or, we handle the reference inside the sub, like
sub listHash {
my ($hashref) = #_;
foreach my $key (sort keys %$hashref) {
my $value = $hashref->{$key};
print "$key => $value\n";
}
}
Notice how the reference uses the dereference arrow -> to access hash entries, and how it is dereferenced to a hash for keys.
I suspect that your suspicion is correct. In your method sub listHash you're correctly passing in the hash but you're trying to use a hash instead of a hash reference for the internal variable. Try using my ($hash) = #_; instead of my %hash = #_;.
When using references you can use the -> operator to de-reference it to get to the underlying values. The rest of your method should look like this:
sub listHash
{
my ($hash) = #_;
foreach my $key (sort keys %{$hash}) {
my $value = $hash->{$key};
message("$key => $value\n");
}
}
On line 43 of your program I had to tell Perl that the reference should be a hash reference by calling keys %{$hash}. Then on line 44 I de-referenced the hash to get the correct value by calling $hash->{$key}. For more information on Perl and references you can read the through the tutorial.
listHash is expecting a hash and you're passing it a hash reference. Change:
listHash(\%bo_ref);
to:
listHash(%bo_ref);

Perl objects error: Can't locate object method via package

I realise there are several questions like this out in the ether, but I can't a solution for my problem. Maybe I should improve my lateral thinking.
I have a module which I am testing. This module looks something like:
package MyModule;
use strict;
use warnings;
... # a bunch of 'use/use lib' etc.
sub new {
my $class = shift;
my ($name,$options) = #_;
my $self = {
_name => $name,
_features => $options,
_ids => undef,
_groups => undef,
_status => undef,
};
bless $self,$class;
return $self;
}
sub init {
my ($self) = #_;
my ($ids,$groups,$status) = ...; # these are from a working module
$self->{_ids} = $ids;
$self->{_groups} = $groups;
$self->{_status} = $status;
return $self;
}
This is my test file:
#!/usr/bin/perl -w
use strict;
use MyModule;
use Test::More tests => 1;
use Data::Dumper;
print "Name: ";
my $name;
chomp($name = <STDIN>);
print "chosen name: $name\n";
my %options = (
option1 => 'blah blah blah',
option2 => 'blu blu blu',
);
my $name_object = MyModule->new($name,\%options);
print Dumper($name_object);
isa_ok($name_object,'MyModule');
$name_object->init;
print Dumper($name_object);
Now it works down to the isa_ok, but then comes up with:
Can't locate object method "init" via package "MyModule" at test_MyModule.t line 31, <STDIN> line 1.
This has only occurred now that I'm trying (and somewhat failing it seems) to use objects. So thus I reckon I'm misunderstanding the applications of objects in Perl! Any help would be appreciated...
I think you're loading a different file than the one you think you are loading.
print($INC{"MyModule.pm"}, "\n");
will tell you which file you actually loaded. (If the module name is really of the form Foo::Bar, use $INC{"Foo/Bar.pm"}.) Make sure the capitalisation of the package and the file name match.

Accessing hash of hashes defined in another file in perl and printing it

Now my file1 contains the hash of hashes as shown below:
package file1;
our %hash = (
'articles' => {
'vim' => '20 awesome articles posted',
'awk' => '9 awesome articles posted',
'sed' => '10 awesome articles posted'
},
'ebooks' => {
'linux 101' => 'Practical Examples to Build a Strong Foundation in Linux',
'nagios core' => 'Monitor Everything, Be Proactive, and Sleep Well'
}
);
And my file2.pl contains
#!/usr/bin/perl
use strict;
use warnings;
require 'file1';
my $key;
my $key1;
for $key (keys %file1::hash){
print "$key\n";
for $key1 (keys %{$file1::hash{$key1}}){
print "$key1\n";
}
}
Now my question is, I get an error
"Use of uninitialized value in hash element at file2.pl"
when I try to access the hash like this:
for $key1 (keys %{$file1::hash{$key1}})
Kindly help.
It's because $key1 is not defined.
You meant to use %{ $file1::hash{$key} } instead.
Note that if you avoid pre-declaring $key1, the strict pragma can catch it at compile-time:
for my $key (keys %file1::hash){
print "$key\n";
for my $key1 (keys %{$file1::hash{$key1}}){
print "$key1\n";
}
}
Message
Global symbol "$key1" requires explicit package name