Single parameters to new() must be a HASH ref data - perl

I have a perl script and it works on perl version 5.8.8 but 5.14 got that error: Odd number of elements in anonymous hash at
Here is my code:
$session->begin_privileged({ $_enable_password })
Previously it was like this:
$session->begin_privileged( $_enable_password )
And at this time I get this error:
Single parameters to new() must be a HASH ref data
I have similar typed lines like above and I get same Single parameters error on each.
I googled it but could not find a regular solution.

If $session is an instance of Net::Appliance::Session then your call should look like this:
$session->begin_privileged({ password => $_enable_password });
But I am still not sure that $_enable_password isn't a hash reference in the first place, in which case you should pass it as a single parameter without enclosing braces. It is a much more likely explanation that $_enable_password isn't being set up correctly than that Perl v14 has stopped it working.

Related

Perl references. How do we know it is one?

I am new to Perl and reading about references.
I can not understand how doe one know if the variable he work on is a reference.
For instance if I understand correctly, this:
$b = $a could be assigning scalars or references. How do we know which is it?
In C or C++ we would know via the function signature (*a or &a of **a). But in Perl there is no signature of parameters.
So how do we know in code what is a reference and what is not? Or if it is a reference to scalar or array or hash or another reference?
Perl has a ref that you can use for that:
Returns a non-empty string if EXPR is a reference, the empty string otherwise. [...]
The string returned (if non-empty) will tell you the type of object the reference references.
You're asking the wrong question.
While there is a function called ref and another called reftype, these are not functions you should ever need to use.
It's bad to check the type of variables, because there's no way to effectively know without actually using it as intended due to overloading and magic.
For example, say you designed a function that accepts a reference or a string. That would be a bad design because an object that overloads stringification is both.
A good interface would use context to differentiate the arguments. For example, it could differentiate based on the number of arguments,
foo($point_obj)
-vs-
foo(x => $x, y => $y)
based on the value of other arguments,
foo(fh => $fh)
-vs-
foo(str => $file_contents)
or based on the choice of function called
foo_from_fh($fh)
-vs-
foo($file_contents)
So the answer is: You know it's a reference because your documentation instructs the caller of your function to pass a reference. If you got passed something other than a reference and it's used as a reference, the caller will get a strict error for their error.
The ref function is what you're looking for. Documentation is available at http://perldoc.perl.org/functions/ref.html
ref EXPR
Returns a non-empty string if EXPR is a reference, the empty string otherwise. If EXPR is
not specified, $_ will be used. The value returned depends on the type of thing the
reference is a reference to...

Perl alternative to hash_hmac('ripemd160', $data, $key) in PHP

I need to produce same result in Perl that hash_hmac('ripemd160', $data, $key) produces in PHP
Managed to trace it down to two perl modules, just cant get them working together...
Digest::HMAC and Crypt::RIPEMD160
use Crypt::RIPEMD160;
use Digest::HMAC;
$hmac = Digest::HMAC->new('bar', 'Crypt::RIPEMD160');
$hmac->add('foo');
$digest = $hmac->digest;
anyone got any ideas what am i doing wrong?
If i use the code above i get following error:
Can't call method "add" on an undefined value at /usr/lib64/perl5/vendor_perl/5.12.4/Digest/HMAC.pm line 28.
Since i was unable to pass the hash function reference in the code above, after looking at the HMAC module at the hmac function i thought i could write it in my code direct:
my $data = 'bar';
my $key = 'foo';
$block_size = 160;
$block_size ||= 64;
$key = Crypt::RIPEMD160->hash($key) if length($key) > $block_size;
my $k_ipad = $key ^ (chr(0x36) x $block_size);
my $k_opad = $key ^ (chr(0x5c) x $block_size);
my $digest = Crypt::RIPEMD160->hash($k_opad, Crypt::RIPEMD160->hash($k_ipad, $data));
this does produce a hash but still a wrong one
PHP generated hash: isceebbf5cd5e34c888b493cf7f7c39a7b181b65a3
The perl hash: hash21a2fa2bf39fd99d4c9cdf147added69c32d45f9e
To be honest i dont care how its done and what modules are used as long as I get same hash as the php function produces... at this point I am tempted writing a php script that i call from perl just to get that hash... :( as I am runing out of ideas...
The Digest::HMAC only includes Digest::HMAC_MD5 and Digest::HMAC_SHA1. However, I took a look at the Perl code for Digest::HMAC_MD5. The whole thing is about 20 lines of code. It basically creates two methods:
sub hmac_md5 {
hmac($_[0], $_[1], \&md5, 64);
}
and
sub hmac_md5_hex {
unpack("H*", &hmac_md5);
}
That's pretty much the entire program.
If you forget about the object oriented style of the package, and use the functional style, it looks like this might work for you:
hmac($data, $key, \&ripemd160, 160);
or maybe just:
hmac($data, $key \&ripemd160);
In fact, that's documented on the CPAN Digest::HMAC page itself.
I am perhaps a bit late in this discussion but when talking about Crypt::Digest::RIPEMD160 (I am the author of this module :) you can easily create HMAC with Crypt::Mac::HMAC from the same family of modules.
It is as simple as:
use Crypt::Mac::HMAC 'hmac';
$hmac_raw = hmac('RIPEMD160', $key, $data);
The reason your code doesn't work is that, while the interface provided by Crypt::RIPEMD160 looks similar to the standard Digest interface, it's not quite compatible: in particular, the reset() method of Crypt::RIPEMD160 apparently doesn't return a reference to the object it's called on, and the code in Digest::HMAC happens to rely on that detail.
This incompatibility would be a trivial things to fix by slightly tweaking either module, either to add the missing return value to Crypt::RIPEMD5 or to make Digest::HMAC less reliant on needless method chaining. The latter would be as easy as changing the line:
$self->{hasher}->reset->add($self->{k_opad}, $inner_digest);
in Digest::HMAC to:
$self->{hasher}->reset;
$self->{hasher}->add($self->{k_opad}, $inner_digest);
(Of course, I'm not suggesting that you do this yourself, although you could report the issue to the maintainers of those modules.)
However, with both modules as they currently are, it just won't work. The solutions I'd recommend would be to either use the non-OO interface, as David W. suggests, or try the newer Crypt::Digest::RIPEMD160 module, which properly implements the Digest interface and should play nicer with Digest::HMAC.
Edit:
Actually, David W.'s suggestion won't work as given, because Crypt::RIPEMD160 doesn't export a non-OO ripemd160() function. You could, however, easily create one:
use Crypt::RIPEMD160;
sub ripemd160 {
return Crypt::RIPEMD160->hash( join "", #_ );
}
and then use it like this:
use Digest::HMAC qw( hmac );
sub hmac_ripemd160 {
return hmac( #_[0, 1], \&ripemd160, 64 );
}
(Yes, 64 bytes is the correct block size from HMAC-RIPEMD160, since the input block length of RIPEMD160 is 16 32-bit words, which equals 512 bits or 64 bytes. In practice, using the wrong input block size is very unlikely to cause any issues, other than for interoperability of course, but the security proof of the HMAC construction assumes, for simplicity, that the key is padded to be exactly one input block long. Thus, and in order to ensure that all implementations of HMAC-RIPEMD160 produce the same output for the same key and message, it's best to stick to this rule.)
Edit 2: OK, I tried to test the code I posted above against the HMAC-RIPEMD160 test vectors from RFC 2286, and just could not get the results to match. What I finally realized was two things:
The non-OO hmac() function exported by Digest::HMAC assumes that the custom hash function passed to it will accept multiple parameters and concatenate them. My original implementation of the ripemd160() wrapper above did not (but I fixed it so that now it does). This is arguably a bug in Digest::HMAC, or at least in its documentation.
The Crypt::RIPEMD160 module comes with the submodule Crypt::RIPEMD160::MAC, which already implements HMAC-RIPEMD160, even though, for some perverse reason, the documentation doesn't actually use the name HMAC. If you look at the code, though, or just compare the output to the official test vectors, that's indeed exactly what it does.

Perl subroutine getting arguments without sending any

I'm attempting to do some hacking in some Git source code (as in the source code for Git, not just some random piece of code managed by Git). The bit I'm looking at is in Perl, and I'm having trouble understanding what's going on.
I have very little experience (and that several years old) of Perl; I've asked a couple of friends with more experience for advice, but they've turned up nothing.
The relevant bit of code is in the v1.8.1.5 source code, where git-svn.perl's cmd_fetch function includes the line:
$_fetch_all ? $gs->fetch_all : $gs->fetch;
My best reading of this is that it will call either the fetch or fetch_all functions (I can't see how it could be doing anything else, certainly).
In SVN.pm we find that fetch function, which starts with the following line:
my ($self, $min_rev, $max_rev, #parents) = #_;
I recognise that as collecting the function arguments, but (and finally, my question): where do these arguments get passed in?
The function called with the arrow notation is called as a method. The first argument to a method is the object whose method was called. $self will be therefore set to $gs. The rest of the arguments is empty, hence undef.
First, I really hope there is an assignment to the left of the code you cited. Using the conditional operator for control flow is a crime against humanity. That said, your intuition about what happens is correct: Depending on the value of $_fetch_all, either $gs->fetch or $gs->fetch_all is called. Now, on to the argument question.
Perl method calls pass arguments by prepending the invocant to the list of arguments, so the call
$gs->fetch
results in the arguments ($gs) being passed into the method as #_. The argument assignment line
my ($self, $min_rev, $max_rev, #parents) = #_;
then list-assigns
my ($self, $min_rev, $max_rev, #parents) = ($gs);
List assignments assign corresponding elements until an array or hash on the left-hand side eats all the arguments or the list of assignees is exhausted, padding the list with undef as needed. So $self gets $gs, $min_rev and $max_rev get undef, and #parents gets the empty list. It turns out that these are all valid values, and so nothing untoward happens.
If you wanted to affect the values of $min_rev et al., you would alter the call site to read
$gs->fetch(5, 9)
(it turns out #parents is ignored, so I don't know what its legal values might be).

Can I call a Perl OO function without first saving the object to a variable?

How can I turn this two statement snippet into a single statement?
my $handle = &get_handle('parameter');
$handle->do_stuff;
Something like {&get_handle('parameter')}->do_stuff;, but what would be the correct syntax?
There's no requirement for a variable to be used on the left-hand side of the ->. It can be any expression, so you can simply use
get_handle('parameter')->do_stuff
It's actually quite common. For example,
$self->log->warn("foo"); # "log" returns the Log object.
$self->response->redirect($url); # "response" returns a Response object.
$self->config->{setting}; # "config"s return a hash.
get_handle('parameter')->do_stuff
Related: When should I use the & to call a Perl subroutine?

Perl Win32::API() return type

Can anyone give an example of how a string can be returned from a call using Win32::API() function? I need to return a string and print using $val. Please give an example if the same can be handled using pointer as return type.
use Win32::API;
my $res = new Win32::API('abc.dll','MyFun','_argument type list_','_Return type list_')or die $^E;
my $val= $res->Call();
print ($val);
The documentation for Win32::API's Call() method suggests that you must pass Call() a scalar which will be used as a buffer to store the returned value; Call() itself will return whether the call succeeded or not.
Example:
my $return_buffer = " " x 80;
if ($res->Call(80, $return_buffer)) {
print "OK, the API call returned '$return_buffer'\n";
} else {
print "The API call failed for some reason.\n";
}
EDIT: quoting from the docs for completeness:
The two parameters needed here are the length of the buffer that will hold the returned temporary path, and a pointer to the buffer itself. For numerical parameters, you can use either a constant expression or a variable, while for pointers you must use a variable name (no Perl references, just a plain variable name). Also note that memory must be allocated before calling the function, just like in C. For example, to pass a buffer of 80 characters to GetTempPath(), it must be initialized before with:
$lpBuffer = " " x 80;
This allocates a string of 80 characters. If you don't do so, you'll probably get Runtime exception errors, and generally nothing will work. The call should therefore include:
$lpBuffer = " " x 80;
$GetTempPath->Call(80, $lpBuffer);
And the result will be stored in the $lpBuffer variable. Note that you don't need to pass a reference to the variable (eg. you don't need \$lpBuffer), even if its value will be set by the function.
I don't see any obvious problem with the way you are doing this. The Win32::API module is capable of receiving a char * from a DLL function and transforming it into a Perl scalar. This code, for example, does what I expect:
use Win32::API;
$GetCommandLine = Win32::API->new('kernel32',
'LPTSTR GetCommandLine()');
$val = $GetCommandLine->Call();
print "The command line of this program is: $val\n";
which is to print
The command line of this program is: C:\strawberry\perl\bin\perl.exe win32-api-string.pl
The obvious things are to check the return values as well as $! and $^E from every step of your code and that abc.dll is in your program's $PATH. You might want to drop the .dll from the function call (just say Win32::API->new('abc', ...) ) -- none of the examples ever explicitly include the .dll extension, and perhaps the module assumes that you won't use it (and will try to load a library from abc.dll.dll instead).
You also might want to try using the Win32::API constructor from a prototype, as I have done in my example. I find that this gives me fewer headaches setting the right argument and return types properly (but occasionally more headaches trying to shoe horn some object type into the list of types that Win32::API supports out of the box). (The parameter list style constructor is now deprecated anyway, according to the v0.59 docs).