Why does a function name have to be specified in a use statement? - function

In perl, sometimes it is necessary to specify the function name in the use statement.
For example:
use Data::DPath ('dpath');
will work but
use Data::DPath;
won't.
Other modules don't need the function names specified, for example:
use WWW::Mechanize;
Why?

Each module chooses what functions it exports by default. Some choose to export no functions by default at all, you have to ask for them. There's a few good reasons to do this, and one bad one.
If you're a class like WWW::Mechanize, then you don't need to export any functions. Everything is a class or object method. my $mech = WWW::Mechanize->new.
If you're a pragma like strict then there are no functions nor methods, it does its work simply by being loaded.
Some modules export waaay too many functions by default. An example is Test::Deep which exports...
all any array array_each arrayelementsonly arraylength arraylengthonly bag blessed bool cmp_bag cmp_deeply cmp_methods cmp_set code eq_deeply hash
hash_each hashkeys hashkeysonly ignore Isa isa listmethods methods noclass
none noneof num obj_isa re reftype regexpmatches regexponly regexpref
regexprefonly scalarrefonly scalref set shallow str subbagof subhashof
subsetof superbagof superhashof supersetof useclass
The problem comes when another module tries to export the same functions, or if you write a function with the same name. Then they clash and you get mysterious warnings.
$ cat ~/tmp/test.plx
use Test::Deep;
use List::Util qw(all);
$ perl -w ~/tmp/test.plx
Subroutine main::all redefined at /Users/schwern/perl5/perlbrew/perls/perl-5.20.2/lib/5.20.2/Exporter.pm line 66.
at /Users/schwern/tmp/test.plx line 2.
Prototype mismatch: sub main::all: none vs (&#) at /Users/schwern/perl5/perlbrew/perls/perl-5.20.2/lib/5.20.2/Exporter.pm line 66.
at /Users/schwern/tmp/test.plx line 2.
For this reason, exporting lots of functions is discouraged. For example, the Exporter documentation advises...
Do not export method names!
Do not export anything else by default without a good reason!
Exports pollute the namespace of the module user. If you must export try to use #EXPORT_OK in preference to #EXPORT and avoid short or common symbol names to reduce the risk of name clashes.
Unfortunately, some modules take this too far. Data::DPath is a good example. It has a really clear main function, dpath(), which it should export by default. Otherwise it's basically useless.
You can always turn off exporting with use Some::Module ();.

The reason is that some modules simply contain functions in them and they may or may not have chosen to export them by default, and that means they may need to be explicitly imported by the script to access directly or use a fully qualified name to access them. For example:
# in some script
use SomeModule;
# ...
SomeModule::some_function(...);
or
use SomeModule ('some_function');
# ...
some_function(...);
This can be the case if the module was not intended to be used in an object-oriented way, i.e. where no classes have been defined and lines such as my $obj = SomeModule->new() wouldn't work.
If the module has defined content in the EXPORT_OK array, it means that the client code will only get access to it if it "asks for it", rather than "automatically" when it's actually present in the EXPORT array.
Some modules automatically export their content by means of the #EXPORT array. This question and the Exporter docs have more detail on this.
Without you actually posting an MCVE, it's difficult to know what you've done in your Funcs.pm module that may be allowing you to import everything without using EXPORT and EXPORT_OK arrays. Perhaps you did not include the package Funcs; line in your module, as #JonathanLeffler suggested in the comments. Perhaps you did something else. Perl is one of those languages where people pride themselves in the TMTOWTDI mantra, often to a detrimental/counter-productive level, IMHO.
The 2nd example you presented is very different and fairly straightforward. When you have something like:
use WWW::Mechanize;
my $mech = new WWW::Mechanize;
$mech->get("http://www.google.com");
you're simply instantiating an object of type WWW::Mechanize and calling an instance method, called get, on it. There's no need to import an object's methods because the methods are part of the object itself. Modules looking to have an OOP approach are not meant to export anything. They're different situations.

Related

how to resolve "conflicts with" errors in d?

I'm trying to compile some D. The code that I've written uses the std.string library as well as std.algorithm. One of my functions calls indexOf on a string: unfortunately, apparently there's also a indexOf function in std.algorithm, and the compiler doesn't like it:
assembler.d(81): Error: std.algorithm.indexOf!("a == b", string, immutable(char)).indexOf at /usr/share/dmd/src/phobos/std/algorithm.d(4431) conflicts with std.string.indexOf!(char).indexOf at /usr/share/dmd/src/phobos/std/string.d(334)
assembler.d(81): Deprecation: function std.algorithm.indexOf!("a == b", string, immutable(char)).indexOf is deprecated
How do I get around this? In C++ I could use the :: to explicitly say what namespace I'm in... what about D?
If you want to call std.string.indexOf explicitly, then do std.string.indexOf(str, c) instead of indexOf(str, c) or str.indexOf(c).
Or you can use an alias:
alias std.string.indexOf indexOf;
If you put that inside the function where you're calling indexOf, then it should then consider indexOf to be std.string.indexOf for the rest of the function. Or if you put it at the module level, then it'll affect the whole module.
However, due to a bug, UFCS (Universal Function Call Syntax) doesn't currently work with local aliases, so if you put the alias within the function, you'll have to do indexOf(str, c) instead of str.indexOf(c).
A third option is to use a selective import:
import std.string : indexOf;
With that import, only indexOf is imported from std.string, and when you use indexOf, it'll use the string version (even if you've also import std.algorithm). And you can even import std.string regularly in addition to the selective import to get the rest of std.string, and the selective import will still fix the conflict (in which case, it's really not that different from importing std.string and then aliases indexOf). However, due to a bug, selective imports are always treated as public, so doing a selective import of indexOf in a module will affect every module that imports it (potentially causing new conflicts), so you may want to avoid it at this point.

How do XQuery function namespaces work?

EDIT
I want to group together related functions to show that they are related.
If I have local:f1() and local:f2() then I could just change their names to local:menu-f1() and local:menu-f2() but is there a mechanism in the XQuery language to group related functions?
OP
I am very excited to discover that XQuery functions can be declared in a namespace other than local:. Where can I find info about how this works?
Having always declared functions in this way;
declare function local:foo() {
3+4
};
.. and used them in this way;
local:foo()
.. I discover that they can be declared like this;
declare namespace baz = "fred:bloggs";
declare function baz:foo() {
3+4
};
.. and used like this;
baz:foo()
But I can only find reference-like information about declare namespace and declare function separately, not tutorial-like information about how XQuery function namespaces work in general.
Is there a newbie guide to XQuery function namespaces?
I'm using a Saxon processor - XQuery 1.0.
What you are probably using are normal XQuery namespaces - what you probably are looking for are modules. You can put a bunch of functions in its own module namespace like this:
module namespace foo = "http://www.myurl.com/foo";
declare function foo:bar($args as item()*) as item()* {
() (: do something cool :)
};
Afterwards you can import the module in you main query and call the function:
import module namespace foo = "http://www.myurl.com/foo";
foo:bar(<my-element/>)
The problem is, that it is not standardized, how the processor has to find the query. And I don't know how Saxon implements the module resolving mechanism (you should look into the documentation and/or write to the Saxon mailing list).
But most XQuery processors look at the path given by an "at" clause relative from the location of the query. So to have something that should work on most implementations: For example you could store the module in a file named foo.xq and place it into the same directory than your main query and then for the module import you would write:
import module namespace foo = "http://www.myurl.com/foo" at "foo.xq";
which gives a hint to the XQuery engine where it should look for the module.
You can find some (not a lot at the moment) documentation about this stuff at http://www.xquery.me/ - hope this helps.
EDIT
Ok I see, you only want to group your functions. To do that you already figured out everything you need to know. But I still want to emphasize that splitting your query up into modules would probably be the better solution for your use-case (it's just somehow nicer, since your have more modularity and in the upcoming XQuery 3.0 recommendation you will even have the possibility to put stuff like private functions and variables in there). But if your query does not get big, your solution is of course also ok.
You can think about XML namespaces the same way you would think about namespaces in C++. In XQuery, functions, elements, collections, variables, attributes etc can be in an own namespace (again - like in C++). There are some implicitely defined namespaces like xs (the XML Schema namespace where you can find the data types like boolean, integer etc), local (a namespace where you can put in functions so that you are not forced to define your own namespace in a main query), fn (where all functions from the "XQuery 1.0 and XPath 2.0 functions and operators" recommendation are defined). But the prefix of this function is only an alias - you can use whatever you want.
So let's say you have the following code in the prolog of your query:
declare namespace blubb = "http://www.w3.org/2001/XMLSchema";
blubb:integer would be exactly the same type than xs:integer - the same holds for functions:
declare namespace l = "http://www.w3.org/2005/xquery-local-functions";
With declaring that you can access every function in the local namespace with the "l" prefix (so l:bar() if local:bar() exists).
If you do not type a prefix, XQuery assumes that this function is in the "fn" namespace. This is why bot
fn:concat("Hello ", "World!")
and
concat("Hello ", "World!")
are equivalent. You can change this behavior. You could include this line into the prolog:
declare default function namespace "http://www.w3.org/2005/xquery-local-functions";
which would tell the XQuery processor that you do not want to prefix local functions (so bar() would be equivalent to local:bar()).
I am not sure if I answered your questions or at least was able to bring in some clarity. I do not know about a tutorial for that (since in the beginning it is somehow confusing but in the end you realize that there is not a lot to say about since the mechanisms are much simpler than they look in the first place). The document where I always look up stuff is the recommendation at http://www.w3.org/TR/xquery/
If this does not help you please try to qualify and I can try again with an explanation..

Actionscript 3 - passing custom class as parameter to custom class where parameter class not constructed

Hi and thanks in advance,
I have a custom class being constructed from my main class. In the custom class it has another custom class that is passed in as a parameter. I would like to strictly type the parameter variable but when I do, 'the type is not a compile type constant etc'.
This, I understand, is because the custom class used as a parameter has not yet been constructed.
It all works when I use the variable type ( * ) to type the parameter.
I suspect this is a design flaw, in that I am using an incorrect design pattern. It is actually hand-me-down code, having received a large project from someone else who is not entirely familiar with oop concepts and design patterns.
I have considered using a dummy constructor for the parametered class in my main class but the passed in class also takes a custom class (itself with a parametered constructor). I am considering using ... (rest) so that the custom classes' parameters are optional.
Is there any other way to control the order of construction of classes? Would the rest variables work?
Thanks
(edit)
in main.as within the constructor or another function
var parameter1:customclass2;
customclass1(parameter1);
in customclass1 constructor:
public function customclass1(parameter1:customclass2)
{
....
Flash complains that the compiled type cannot be found when I use the data type customclass 2 in the paramater. It does not complain when I use the variable data type * or leave out the data type (which then defaults to * anyway). I reason that this is because customclass2 has not yet been constructed and is therefore not available to the compiler.
Alternatively, I have not added the path of customclass2 to the compiler but I am fairly certain I have ruled this out.
There are over 10,000 lines of code and the whole thing works very well. I am rewriting simply to optimise for the compiler - strict data typing, error handling, etc. If I find a situation where inheritance etc is available as an option then I'll use it but it is already divided into classes (at least in the main part). It is simply for my own peace of mind and to maintain a policy of strict data typing so that compiler optimization works more efficiently.
thnx
I have not added the path of customclass2 to the compiler but I am fairly certain I have ruled this out.
So if you don't have the class written anywhere what can the compiler do ? It is going to choke of course. You either have to write the CustomClass class file or just use "thing:Object" or "thing:Asteriks". It's not going to complain when you use the "*" class type because it could be anything an array, string, a previously declared class. But when you specify something that doesn't exists it will just choke, regardless of the order the parameters are declared in.

How to define an function in the eshell (Erlang shell)?

Is there any way to define an Erlang function from within the Erlang shell instead of from an erl file (aka a module)?
Yes but it is painful. Below is a "lambda function declaration" (aka fun in Erlang terms).
1> F=fun(X) -> X+2 end.
%%⇒ #Fun <erl_eval.6.13229925>
Have a look at this post. You can even enter a module's worth of declaration if you ever needed. In other words, yes you can declare functions.
One answer is that the shell only evaluates expressions and function definitions are not expressions, they are forms. In an erl file you define forms not expressions.
All functions exist within modules, and apart from function definitions a module consists of attributes, the more important being the modules name and which functions are exported from it. Only exported functions can be called from other modules. This means that a module must be defined before you can define the functions.
Modules are the unit of compilation in erlang. They are also the basic unit for code handling, i.e. it is whole modules which are loaded into, updated, or deleted from the system. In this respect defining functions separately one-by-one does not fit into the scheme of things.
Also, from a purely practical point of view, compiling a module is so fast that there is very little gain in being able to define functions in the shell.
This depends on what you actually need to do.
There are functions that one could consider as 'throwaways', that is, are defined once to perform a test with, and then you move on. In such cases, the fun syntax is used. Although a little cumbersome, this can be used to express things quickly and effectively. For instance:
1> Sum = fun(X, Y) -> X + Y end.
#Fun<erl_eval.12.128620087>
2> Sum(1, 2).
3
defines an anonymous fun that is bound to the variable (or label) Sum. Meanwhile, the following defines a named fun, called F, that is used to create a new process whose PID (<0.80.0>) is bound to Pid. Note that F is called in a tail recursive fashion in the second clause of receive, enabling the process to loop until the message stop is sent to it.
3> Pid = spawn(fun F() -> receive stop -> io:format("Stopped~n"); Msg -> io:format("Got: ~p~n", [Msg]), F() end end).
<0.80.0>
4> Pid ! hello.
hello
Got: hello
5> Pid ! stop.
Stopped
stop
6>
However you might need to define certain utility functions that you intend to use over and over again in the Erlang shell. In this case, I would suggest using the user_default.erl file together with .erlang to automatically load these custom utility functions into the Erlang shell as soon as this is launched. For instance, you could write a function that compiles all the Erlang files in living in the current directory.
I have written a small guide on how to do this on this GitHub link. You might find it helpful and instructive.
If you want to define a function on the shell to use it as macro (because it encapsulates some functionality that you need frequently), have a look at
https://erldocs.com/current/stdlib/shell_default.html

How to resolve naming conflicts when multiply instantiating a program in VxWorks

I need to run multiple instances of a C program in VxWorks (VxWorks has a global namespace). The problem is that the C program defines global variables (which are intended for use by a specific instance of that program) which conflict in the global namespace. I would like to make minimal changes to the program in order to make this work. All ideas welcomed!
Regards
By the way ... This isn't a good time to mention that global variables are not best practice!
The easiest thing to do would be to use task Variables (see taskVarLib documentation).
When using task variables, the variable is specific to the task now in context. On a context switch, the current variable is stored and the variable for the new task is loaded.
The caveat is that a task variable can only be a 32-bit number.
Each global variable must also be added independently (via its own call to taskVarAdd?) and it also adds time to the context switch.
Also, you would NOT be able to share the global variable with other tasks.
You can't use task variables with ISRs.
Another Possibility:
If you are using Vxworks 6.x, you can make a Real Time Process application.
This follows a process model (similar to Unix/Windows) where each instance of your program has it's own global memory space, independent of any other instance.
I had to solve this when integrating two third-party libraries from the same vendor. Both libraries used some of the same symbol names, but they were not compatible with each other. Because these were coming from a vendor, we couldn't afford to search & replace. And task variables were not applicable either since (a) the two libs might be called from the same task and (b) some of the dupe symbols were functions.
Assume we have app1 and app2, linked, respectively, to lib1 and lib2. Both libs define the same symbols so must be hidden from each other.
Fortunately (if you're using GNU tools) objcopy allows you to change the type of a variable after linking.
Here's a sketch of the solution, you'll have to modify it for your needs.
First, perform a partial link for app1 to bind it to lib1. Here, I'm assuming that you've already partially linked *.o in app1 into app1_tmp1.o.
$(LD_PARTIAL) $(LDFLAGS) -Wl,-i -o app1_tmp2.o app1_tmp1.o $(APP1_LIBS)
Then, hide all of the symbols from lib1 in the tmp2 object you just created to generate the "real" object for app1.
objcopymips `nmmips $(APP1_LIBS) | grep ' [DRT] ' | sed -e's/^[0-9A-Fa-f]* [DRT] /-L /'` app1_tmp2.o app1.o
Repeat this for app2. Now you have app1.o and app2.o ready to link into your final application without any conflicts.
The drawback of this solution is that you don't have access to any of these symbols from the host shell. To get around this, you can temporarily turn off the symbol hiding for one or the other of the libraries for debugging.
Another possible solution would be to put your application's global variables in a static structure. For example:
From:
int global1;
int global2;
int someApp()
{
global2 = global1 + 3;
...
}
TO:
typedef struct appGlobStruct {
int global1;
int global2;
} appGlob;
int someApp()
{
appGlob.global2 = appGlob.global1 + 3;
}
This simply turns into a search & replace in your application code. No change to the structure of the code.