Can you please tell me the steps I need to follow in order to obtain an account on CPAN? I'd like to contribute some modules. A while back, I tried to create an account, and I remember I got back a mail containing some of this text:
The following links are only valid for PAUSE maintainers: and there were 2 links :
Registration form with editing capabilities:and
Immediate (one click) registration:I remember I clicked on the Immediate registration but it asked me for a username & password.I did not knew how to go on from there. Was I going in the wrong direction? Does anyone have a step by step account registration tutorial?
Are there any algorithms available for analyzing the complexity of an image? Basically I'm writing a Perl script that will use the system() function to launch MPlayer in the background to generate 10 to 20 screenshots for the input video file and I'd like it to be able to discard any simple images such as a shot of the sky, or a black background, and other simple images and keep just 3 of those images with the highest complexity or most number of colors. Is there a module or a separate program I can use to accomplish this? I'm guessing maybe Image::Magick can take care of this.
I'm trying to get perl running under on my Apache 2 macports install. I'm hoping an experienced perl geek can help me out. I've...
Written the following test script in htdocs
#!/opt/local/bin/perl
print "content-type: text/html \n\n";
print 'Hello world.';
All I get is the script contents printed out to the screen. Am I missing a step? Is there some additional configuration I need to do in the .conf file?
I want to delete from many files each instance of a paragraph. I call paragraph a sequence of lines.
For example:
my first line my second line my third line the fourth 5th and last
the problem is that I only want to delete them when they appear as a group. For example, if
my first lineappears alone I don't want to delete it.
I am new with Perl. I'm following a bioinformatics webapi and I'm attempting to simply display the value stored in $result. My print "$result\n"; command doesn't appear to be functioning. What are some possibilities as to what is going on here?
# #!/usr/local/bin/perl
use strict;
# 1. include SOAP Lite
use SOAP::Lite;
# 2. specifies WSDL file
my $service = SOAP::Lite -> service('http://xml.nig.ac.jp/wsdl/GetEntry.wsdl');
# 3. call SOAP service
my $result = $service->getXML_DDBJEntry("AB000003");
print "$result\n";
I have never used DBIx::Class until today, so I'm completely new at it.
I'm not sure if this is possible or not, but basically I have a table in my SQLite database that has a timestamp column in it. The default value for the timestamp column is "CURRENT_TIMESTAMP". SQLite stores this in the GMT timezone, but my server is in the CDT timeszone.
My SQLite query to get the the timestamp in the correct timezone is this:
select datetime(timestamp, 'localtime') from mytable where id=1;
I am wondering if it is possible in my DBIx schema for "MyTable" to force it to apply the datetime function every time it is retrieving the "timestamp" field from the database?
In the cookbook it looks like it is possible to do this when using the ->search() function, but I am wondering if it's possible to make it so if I'm using search(), find(), all(), find_or_new(), or any function that will pull this column from the database, it will apply the datetime() SQLite function to it?
DBIx::Class seems to have great documentation - I think I'm just so new at it I'm not finding the right places/things to search for.
Thanks in advance!
Does anyone know how to prepare data to plot a CDF (I have a bunch of floating point numbers)? I was planning on using gnuplot and on first look, the Statistics::Descriptive module seemed the best fit but looks like I might need some help here.
I recently saw someone with a T-shirt with some Perl code on the back. I took a photograph of it and cropped out the code:

Next I tried to extract the code from the image via OCR, so I installed Tesseract OCR and the Python bindings for it, pytesser.
Pytesser only works on TIFF images, so I converted the image in Gimp and entered the following code (Ubuntu 9.10):
>>> from pytesser import *
>>> image = Image.open('code.tif')
>>> print image_to_string(image)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "pytesser.py", line 30, in image_to_string
util.image_to_scratch(im, scratch_image_name)
File "util.py", line 7, in image_to_scratch
im.save(scratch_image_name, dpi=(200,200))
File "/usr/lib/python2.6/dist-packages/PIL/Image.py", line 1406, in save
save_handler(self, fp, filename)
File "/usr/lib/python2.6/dist-packages/PIL/BmpImagePlugin.py", line 197, in _save
raise IOError("cannot write mode %s as BMP" % im.mode)
IOError: cannot write mode RGBA as BMP
>>> r,g,b,a = image.split()
>>> img = Image.merge("RGB", (r,g,b))
>>> print image_to_string(img)
Tesseract Open Source OCR Engine
éi _ l_` _ t
’ ‘" fY`
{ W IKQW
· __·_ ‘ ·-»·
:W Z
·· I A n 1
;f
` `
`T .' V _ ‘
I {Z.; » ;,. , ; y i- 4 : %:,,
`· » V; ` ?
‘,—·.
H***li¥v·•·}I§¢ ` _ »¢is5#__·¤G$++}§;“»‘7·
71 ’ Q { NH IQ
ytéggygi { ;g¤qg;gm·;,g(g,,3) {3;;+-
§ {Jf**$d$ }‘$p•¢L#d¤ Sc}
» i ` i A1:
That's clearly gibberish that comes out of the OCR engine. So, my question is:
Line directives are used to reconfigure perl's idea of the current filename and line number. When is this required to get right filename and line number (in an error message)?
I'm continuing to work out of an outdated bioinformatics book and I'm attempting to use the XML::Smart Module.
I suspect the module's methods have changed over the course of 6 years and I'm inexperienced with perl to troubleshoot from cpan source. The commented out code proves the ncbi.gov query functions, I'm having trouble with the 'new' method - it's not parsing the XML. What am I doing wrong? Thanks!
Update Specifically I'm running into trouble with parsing and displaying the Id array: my @Id = $results->{eSearchResult}{IdList}{Id}{'@'}; I'm running this on OSX terminal and I don't see any Ids when I run this script. I am seeing the proper Count. Thanks!
#!/usr/local/bin/perl
# use lib "/Users/fogonthedowns/myperllib";
# use LWP::Simple;
use XML::Smart;
use strict;
#Set base URL for all eutils
my $utils = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils";
my $db = "Pubmed";
my $query ="Cancer+Prostate";
my $retmax = 10;
my $esearch = "$utils/esearch.fcgi?" .
"db=$db&retmax=$retmax&term=";
# my $esearch_result = get($esearch.$query);
# print "ESEARCH RESULT: $esearch_result\n";
# print "Using Query: \n$esearch$query\n";
# print "hello world\n";
my $results = XML::Smart->new($esearch.$query,"XML::Parser");
my $count = $results->{eSearchResult}{Count};
my @Id = $results->{eSearchResult}{IdList}{Id}{'@'};
my $all_Id = join("\n", @Id);
print "Count = $count\n";
print "$all_Id\n";
So again using Moose I write a role like this:
package My::Role;
use Moose::Role;
use Some::Class::Consuming::My::Role;
With the note that Some::Class::Consuming::My::Role consumes the role My::Role;
And what do I get ? I get an error message like this:
A role generator is required to generate roles at /usr/local/share/perl/5.10.0/MooseX/Role/Parameterized/Meta/Role/Parameterizable.pm line 79
MooseX::Role::Parameterized::Meta::Role::Parameterizable::generate_role('MooseX::Role::Parameterized::Meta::Role::Parameterizable=HASH...', 'consumer', 'Moose::Meta::Class=HASH(0x894e540)', 'parameters', 'HASH(0x86fc1e0)') called at /usr/local/share/perl/5.10.0/MooseX/Role/Parameterized/Meta/Role/Parameterizable.pm line 116
MooseX::Role::Parameterized::Meta::Role::Parameterizable::apply('MooseX::Role::Parameterized::Meta::Role::Parameterizable=HASH...', 'Moose::Meta::Class=HASH(0x894e540)', 'element_type', 'Tuple') called at /usr/local/lib/perl/5.10.0/Moose/Util.pm line 132
Moose::Util::_apply_all_roles('Moose::Meta::Class=HASH(0x894e540)', undef, 'CM::Group', 'HASH(0x894e1d0)') called at /usr/local/lib/perl/5.10.0/Moose/Util.pm line 86
Moose::Util::apply_all_roles('Moose::Meta::Class=HASH(0x894e540)', 'CM::Group', 'HASH(0x894e1d0)') called at /usr/local/lib/perl/5.10.0/Moose.pm line 57
Moose::with('Moose::Meta::Class=HASH(0x894e540)', 'Group', 'HASH(0x894e1d0)') called at /usr/local/lib/perl/5.10.0/Moose/Exporter.pm line 293
Moose::with('Group', 'HASH(0x894e1d0)') called at Some_path_on_disk line 6
require Some_other_path_on_disk called at Some_path_on_disk line 9
Group::BEGIN() called at Yet_another_path_on_disk line 0
eval {...} called at Yet_another_path_on_disk line 0
Compilation failed in require at some_path_on_disk line 9.
BEGIN failed--compilation aborted at some_path_on_disk line 9.
What am I to make of this ? As Dijkstra would concisely describe, this looks like "just a meaningless concatenation of words"(which is exactly what it is).
Would a more appropriate error message be "You cannot use a class consuming the role that you are currently defining " ?
In actuality I get one and a half pages of error which is completely unreadable and devoid of any logic or sense of respect for the user that is using Moose (in terms of intuitive error messages) just like the one above.
What's to be done in this case ?
I mean I get on my screen these error messages that are sometimes completely unrelated to the problem that I'm having (which I can assess after solving the problems that probably caused them, I say probably becuase I have no idea where these error messages came from because they look like they fell from the sky as they have no relation to the actual situation). Is this:
Gentlemen, when writing software, please please please, take care of the poor programmer that will use it and respect him by writing relevant error messages.
(Except for error messages Moose is a pretty good piece of software)
If i do this:
GetOptions(
'u=s' => \$in_username,
'r=i' => \$in_readonly,
'b=i' => \$in_backup
);
exit usage() unless $in_username && $in_readonly && $in_backup;
and call the program like this:
./app.pl -u david -r 12 -b 0
it always results in calling usage(), so obviously the 0 is not seen as an integer value. What can i do accept integer values AND 0?
I have a file of 1000 lines, each line has 2 words, seperated by a space. How can I print each line only if the last word length is greater than 7 chars? Can I use awk RLENGTH? is there an easy way in perl?
Why is there no error issued by strict:
use strict;
$a = $a + 1;
I have a doubt in system function.I want to store the system functions output to a variable.
For example,
system("ls");
Here I want all the file names in the current directory to store in a variable.I know that I can do this by redirecting the output into a file and read from that and store that to a variable. But I want a efficient way than that.Is there any way .
Possible Duplicate:
How can I programmatically convert Word doc or docx files into text files?
hi all...
sorry for posting the same question once again.. please see the bewlow link... in that link one program is written for windows system... can anyone know who the program is for linux system..please see the link.. http://stackoverflow.com/questions/1110409/how-can-i-programmatically-convert-word-doc-or-docx-files-into-text-files
i need a way to "saveas" .doc file in open office to .txt .i need a program in Perl which can do that automatically.that means i don't want to open that word document and go to saveas and do it...what i need is i will just give word document name and that script should give the corresponding txt file as output.
one important thing is my system is Linux based one.i saw the same program for windows system here only. but i need this program in Linux. that to "antiword" ,"catdoc","wv ware" commends are not working in my Linux..
please help me regarding this.
thank u in advance.
Possible Duplicate:
How do I Make a new Moose class and instantiate an object of that class at runtime?
How do I build a Moose class at runtime, add a method to it, apply a role to it and instantiate it once? How would you approach this?
After creating a metaclass using Moose::Meta::Class->create, how do I instantiate a real Moose class with that class as a metaclass?
(I need to create the metaclass also because I also want to apply some roles to it.)
I define a method inside a parametrized role that needs to create a new class at run time
using Moose::Meta::Class->create and apply that exact parametrized role to it. I am also making a new method for that role using
$new_class->meta->add_method( some_name => sub {
my ($self) = @_;
...
})
inside the sub {...} I want to access a method of the consumer class and use it for something, I have tried using $self->get_method, it didn't work, how do I do this?
Please notice that the $self inside the sub above is MooseX::Role::Parameterized::Meta::Role::Parameterizable
I also have another question, if I do this:
my $object = Moose::Meta::Class->create(
"some_type",
);
Why isn't $object of type some_type and it's some ugly MooseX::Role::Parameterized::Meta::Role::Parameterizable and how do I get to the object of type some_type?
I have hack I need to employ under these conditions:
-It's the last page of data.
-It's not the first page, either.
-There's not a page-size-even number of data items.
So I tried this code:
my $use_hack =
$last_page_number == $current_page_number and
$page_number != 1 and
$total_items % $items_per_page != 0;
And I keep getting this warning Useless use of numeric ne (!=) in void context about the last condition and it's evaluating true when $total_items % $items_per_page = 0.
say 'NOT EVEN' if $total_items % $items_per_page != 0; #works properly, though...
I've tried various combinations of parentheses to get it right, but nothing seems to work.
In February I’ve been to the third Biohackathon in Tokyo, sponsored by the Japanese Database Center for Life Science (DBCLS) and Computational Biology Research Center (CBRC). As I’ve been travelling some more since then, I only got around to writing up my personal summary of the week just now. Here we go.
The Biohackathon is an annual meeting of bioinformatics developers. Toshiaki Katayama of the University of Tokyo, and founder of BioRuby, brought the hackathon idea to Japan, and lead the organization of the hackathon in the most perfect way. From the locations and the hotel, to the network and the catering (and the fact that there was catering!), it was all top notch. Not to mention the generosity of the sponsoring institutions to actually invite us all!
Now, where to start. It was such a packed and amazing week, and I feel very lucky for having gotten the chance to attend. Plus, it was my first trip to Japan, so the country itself was exciting enough! The schedule of the hackathon was simple enough: the first day was a symposium with lots of talks and the chance to learn about the other attendees and their projects. Day two to five were dedicated solely to hacking and discussion as people saw fit. It was my first meeting of that kind, and it was exciting to have that much freedom to turn the week into an interesting and useful time.
Arriving on Sunday morning, we first got our toes wet in Japan by placing an order in a noodle kitchen by randomly picking something on the menu. We wandered around the neighborhood of Tokyo University, or Todai, a charming part of town with small, old houses and narrow lanes I didn’t expect in Tokyo, and ended up in a quite amazing whisky bar and made some new friends. Good start.
The first actual hackathon day took us to the CBRC in Odaiba, a new and all shiny stretch of the city along the bay, dedicated to science and technology. But before enjoying the view from the cafeteria, we settled down to listen to talks and introduce ourselves to each other in the breaks. With about 60-ish attendees, the hackathon had a good size, allowing diversity but staying manageable. The idea of posting a mini-bio for each attendee along the walls was fantastic, as you could stroll around and get a good idea of who was there, and from what backgrounds they came.
A few of the participants presented the projects they’re working on, and they were all very interesting. You can find the list of speakers and their slides on the wiki. My colleague Jerven Bolleman presented our RDF efforts at UniProt. The day ended with a very nice buffet and some more socializing, and left everyone energized and motivated for a week of hacking.
The rest of the week took place at DBCLS on Todai campus, where people could form groups to their liking and pick among several rooms for quiet hacking. Inspired by the BioRuby and BioPython folks that were present, I started exploring the RDF support in Perl. We do all our RDF work in Java, as do most Semantic Web people, but I feel that puts off many people. Perl hits a sweet spot with its conciseness and pragmatism, and its position in bioinformatics is traditionally strong. I believe that good Perl support would be a major step forward to making biologists and bioinformaticiens warm up to RDF & co – I wrote a somewhat passionate mail about this on the hackathon mailing list recently, that I will post here, too. Anyway, so there are quite a few RDF-related modules on CPAN, most of them gathered at [http://www.perlrdf.org], and I set out to try and compare them, and write some example code, possibly something to explore the UniProt RDF. While I didn’t get that far due to participating in lots of other discussions, it was very interesting to try this out, and I put a State of RDF in Perl page on the wiki and some example code on github. I also exchanged a lot of mails with Greg Williams of RDF::Trine, which was great. I’ll blog about this subject later.
While there were many different groups hacking away, on text mining and RDF generation and all kinds of things, one subject struck me as the subject of this Biohackathon: URIs. How to publish one’s own data with stable, sensible, and dereferenceable URIs, and what to use in your RDF when linking to others who don’t have such nice URIs? This question was discussed many times during the whole week.
Francois Belleau of bio2rdf led many of the discussions (thanks!), which focused mostly on central naming schemes/services for URIs. There seems to be a conflict between keeping content dereferencable and keeping URLs very stable for use as resource identifiers. For the latter goal you don’t need URLs, any string will do as long as it’s unique and stable. So this goal would benefit from a central registry like, as advocated by Francois, lsrn.org/uniprot/P12345, because it would provide a predictable way of naming things uniquely. But it adds a single point of failure to the dereferencing of content. Andrea Splendiani remarked that he never followed a single URL from RDF anyway, while I argued that linking content is the point of the web and keeps the Semantic Web hackable – that will have to be yet another future blog post, I guess! Using providers’ actual URLs is often crappy because they don’t provide a predictable scheme (a=x&b=y vs. b=y&a=x), and you only get HTML anyway.
Opinions differed, and they still do. We arrived at an agreement on “Polite URIs” towards the end, but the discussion has been re-started on the mailing list.
And we haven’t even mentioned the dismal state of versioned URIs, (like UniProt’s non-existing ones…), which I also discussed with Andrea. He proposed including the entry version into the URI. Whole releases could be done via named graphs, although that sounds complicated. I was concerned about people who don’t care and just want to say “this protein” – for them (i.e., their reasoners), uniprot/P12345/v1 is not the same as uniprot/P12345/v2, but it should be. This seems impossible to resolve, it’s one or the other. Uh, ideas anyone?
I guess you got the idea by now – there was so much more happening this week that I can’t summarize it all. Fortunately, others also wrote about it. Brad Chapman wrote about his SPARQL and Python hacking, and the #biohackathon2010 Twitter tag has lots of interesting tidbits.
Let’s end with paraphrasing Toshiaki’s closing notes: a “clique of the world-top-level developers in bioinformatics” met, some great coding and discussion took place, and now that data providers understand the Semantic Web a lot better, services will come.
Thanks to all organizers, the people at DBCLS and CBRC who made this possible, to the participants who brought so much enthusiasm and knowledge to the event, and to Toshiaki in particular for tirelessly working throughout the week to keep everything running smoothly. And for taking us out for great dinners and giving us a tour of the Human Genome Center super computer in the week after the hackathon!
Sayonara!
I'm following a bioinformatics text, and this represents one of my first perl scripts. While in textmate, this does not produce any result. Is it functioning? I added "hello world" at the bottom and I don't see that when I run the script in textmate. What have I done wrong?
#!/usr/local/bin/perl -w
use lib "/Users/fogonthedowns/myperllib";
use LWP::Simple;
use strict;
#Set base URL for all eutils
my $utils = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils";
my $db = "Pubmed";
my $query ="Cancer+Prostate";
my $retmax = 10;
my $esearch = "$utils/esearch.fcgi?" .
"db=$db&retmax=$retmax&term=";
my $esearch_result = get($esearch.$query);
print "ESEARCH RESULT: $esearch_result\n";
print "Using Query: \n$esearch$query\n";
print "hello world\n";
I'm trying to understand the performance numbers I'm getting and how to determine the optimal number of threads.
I wrote an experimental multi-threaded web client in perl which downloads a page, grabs the source for each image tag and downloads the image - discarding the data.
It uses a non-blocking connect with an initial per file timeout of 10 seconds which doubles after each timeout and retry. It also caches IP addresses so each thread only has to do a DNS lookup once.
The total amount of data downloaded is 2271122 bytes in 1316 files via 2.5Mbit connection from http://hubblesite.org/gallery/album/entire/npp/all/hires/true/ . The thumbnail images are hosted by a company which claims to specialize in low latency for high bandwidth applications.
Wall times are:
1 Thread takes 4:48 -- 0 timeouts
2 Threads takes 2:38 -- 0 timeouts
5 Threads takes 2:22 -- 20 timeouts
10 Threads take 2:27 -- 40 timeouts
50 Threads take 2:27 -- 170 timeouts
In the worst case ( 50 threads ) less than 2 seconds of CPU time are consumed by the client.
avg file size 1.7k
avg rtt 100 ms ( as measured by ping )
avg cli cpu/img 1 ms
The fastest average download speed is 5 threads at about 15 KB / sec overall.
The server actually does seem to have pretty low latency as it takes only 218 ms to get each image meaning it takes only 18 ms on average for the server to process each request:
0 cli sends syn
50 srv rcvs syn
50 srv sends syn + ack
100 cli conn established / cli sends get
150 srv recv's get
168 srv reads file, sends data , calls close
218 cli recv HTTP headers + complete file in 2 segments MSS == 1448
I can see that the per file average download speed is low because of the small file sizes and the relatively high cost per file of the connection setup.
What I don't understand is why I see virtually no improvement in performance beyond 2 threads. The server seems to be sufficiently fast, but already starts timing out connections at 5 threads.
The timeouts seem to start after about 900 - 1000 successful connections whether it's 5 or 50 threads, which I assume is probably some kind of throttling threshold on the server, but I would expect 10 threads to still be significantly faster than 2.
Am I missing something here?
EDIT-1
Just for comparisons sake I installed the DownThemAll Firefox extension and downloaded the images using it. I set it to 4 simultaneous connections with a 10 second timeout. DTM took about 3 minutes to download all the files + write them to disk, and it also started experiencing timeouts after about 900 connections.
I'm going to run tcpdump to try and get a better picture what's going on at the tcp protocol level.
I also cleared Firefox's cache and hit reload. 40 Seconds to reload the page and all the images. That seemed way too fast - maybe Firefox kept them in a memory cache which wasn't cleared? So I opened Opera and it also took about 40 seconds. I assume they're so much faster because they must be using HTTP/1.1 pipelining?
Update: the complete code sample, illustrating the problem.
1 my %val = map { $_ => read_val($_) } (1,2,3);
2
3 sub read_val {
4 open my $fh, '<', 'myfile' or die $!;
5 while (<$fh>) {
6 if ($. == $_[0]) {
7 return $_
8 }
9 }
10 }
Modification of a read-only value attempted at test.pl line 5.
What's going on here?
In the spirit of the "Perl Preamble" where a script works properly whether executed by a shell script interpreter or the Perl interpreter...
I have a Perl script which contains an embedded HTML document (as a "heredoc"), i.e.:
#!/usr/bin/perl
... some Perl code ...
my $html = <<'END' ;
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
... more HTML ...
</HTML>
END
... Perl code that processes $html ...
I would like to be able to work on the HTML that's inside the Perl script and check it out using a web browser, and only run the script when the HTML is the way I want. To accomplish this, I need the file to be openable both as an HTML file and as a Perl script.
I have tried various tricks with Perl comments and HTML comments but can't get it quite perfect. The file as a whole doesn't have to be "strictly legal" HTML (although the embedded document should be)... just displayable in a browser with no (or minimal) Perl garbage visible.
EDIT: Solved! See my own answer
Hello! With the Device::Gsm I can read the sms received on my umts-modem. Sometimes one message is divided in two or more sms because of the limitation of length of one sms. Is there a way to find out if a group of sms is a part of one message? Wammu for example shoes me sms that belong together as one text.
#!/usr/bin/perl
use warnings; use strict;
use Device::Gsm;
my $modem = new Device::Gsm( port => '/dev/ttyUSB0' );
if( $modem->connect() ) {
print "connected!\n";
}
else {
print "sorry, no connection with serial port!\n";
}
my @msg = $modem->messages;
if( @msg ) {
my $n = 0;
for( @msg ) {
my $sms = $_;
next unless defined $sms;
print "\nMESSAGE N. $n\n";
print 'Text [', $sms->text(), "]\n";
$n++;
}
}
else {
print "No message on SIM, or error during read!\n";
}
connected!
MESSAGE N. 0 Text [Message 1 Part 1]
MESSAGE N. 1 Text [Message 1 Part 2]
MESSAGE N. 2 Text [Message 1 Part 3]
MESSAGE N. 3 Text [Message 2 ]
MESSAGE N. 4 Text [Message 3]
Hello, I m looking to separate the database code from the rest of the code in our application and looking to use an ORM framework that will work well for that knowing that the database is not well designed. I looked in other topics and found that most people suggest DBIx:class, Rose:DB:Object... but did not know which one will work best in my case.
Any suggestions are highly appreciated.
Thanks
It’s a common pattern in Perl 5 to use a hash for a subroutine’s arguments, or some of them. Damian Conway explains this pattern in his excellent Perl Best Practices. I’ll first briefly recap the standard forms, then show how you can support both standard arguments and a hash for extra arguments.
The basic form looks like this:
pad({ text=>$line, cols=>20 })
You can actually leave out the curly hash-braces and just pass a list of key-value pairs:
pad( text=>$line, cols=>20 )
That’s what you often see in practice, but Conway argues against doing that. It allows mismatches such as passing cols=>20..21 (two values on the right hand side) to pass compilation.
Most of the time that won’t be a problem in practice, as the values of the pairs will be simple enough. But it’s better to do things in a uniform way that works in all situations, and the sub’s implementation depends on the way of passing the hash.
When passing an explicit hash enclosed in {}, you get it as a reference:
my ($hashref) = @_;
my $foo = $hash->{foo};
Using raw key-value pairs, you directly get a hash:
my %hash = @_;
my $foo = $hash{foo};
Obviously, the latter form does not allow to pass any arguments other than the hash. One more argument against doing that. I often write subs that take the necessary arguments directly, and optional ones, or “configuration” parameters, in a hash that may or may not be passed:
$uniprot->retrieve(@ids, {format=>'rdf', include=>1}):
You can implement once and re-use a routine, say _get_args_and_conf, that handles this distinction between arguments and configuration so that your subs don’t have to. It looks at the arguments, checks if the last one is a hash, and if that’s the case, merges it with the default configuration and returns the arguments and the configuration separately. You would use it like that in your code:
my %RETRIEVE_DEFAULTS = (
format => 'fasta',
debug => 0 );
sub retrieve {
my ($ids_ref, $conf_ref) =
_get_args_and_conf(\%RETRIEVE_DEFAULTS, @_);
# $ids_ref now contains the arguments, here some ids to
# retrieve from uniprot.org, and $conf_ref contains the
# configuration hash with the user's values if given, and the
# default ones otherwise.
}
My implementation looks like that. The meat of the routine, the hash handling, is straight from Conway’s Best Practices.
sub _get_args_and_conf {
my $default_conf_ref = shift;
my @args = @_;
croak "I need at least one argument!" if @_ < 1;
# if last arg is a hash, it's additional configuration
my %defaults = %{$default_conf_ref};
my %conf = ref $args[-1] eq 'HASH' ?
(%defaults, %{pop @args}) : %defaults;
if (@args < 1) {
croak "I need at least one argument in addition to the hash!";
}
# TODO Deal with the case that the argument list is given as a
# reference.
return (\@args, \%conf);
}
I could waste a few days just to enable perl extention, and may be without good news at the end.
So i decide to use PHP’s system(), passthru() function to call the perl script, instead of using perl extention.
Its much easier, and i’ve succesfully execute perl script from php in just a few seconds, haha
Oh NO!! I was wrong ![]()
perl extention was not successfully installed yet
Fatal error: Class ‘Perl’ not found in /home/webuser/helloworld/htdocs/perl.php on line 4