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...
Related
All is in the subject, really.
I fail to see what the difference in behavior is between those two methods for x:
// first version
Method m(ByRef x As whatever)
{
// play with x
}
// second version
Method m(Output x As whatever)
{
// play with x
}
There must be some reason why both those modifiers exist, however my "mastery" (uhm) of the language is not enough to understand the difference. I have tried and read the documentation, search it etc, to no avail so far.
So, what is the difference between those two argument modifiers?
Well those are just "prettifiers", they don't do much in terms of actual language behaviour, and only used to provide documentation. Idea is that arguments documented as ByRef provide both input and output, for example you can pass an array to be sorted, and Output arguments only provide output, for example list of errors. Output modifier was introduced later, and a lot of system code still use ByRef for both use cases.
If argument is actually passed by reference is only determined by method caller, and keyword doesn't really matter. You will call your method as ..m(.parameter) to pass variable by reference, and ..m(parameter) to pass variable by value.
I am working with the map function in Swift. I am seeing use of "$0" and do not know what it means. Is the "$0" a pointer to the current element of the array?
stringArray = newStringArray.map({"\($0)New"})
I wouldn't use the word pointer, but I think you have the right idea. When you use map here, you're taking an array and applying a function to every element in that array. Here, the function takes in one argument (a string) and outputs another string. $0 refers to the first argument to the function you're calling which, in this case, is the only argument.
The anonymous sort of functions you pass to map are called closures. Looking at Apple's official documentation on closures might be helpful! Here's a link: https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html
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).
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?
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).