There's more than one way to do things PerlMonks

### The Monastery Gates

 ( #131=superdoc: print w/replies, xml ) Need Help??

If you're new here please read PerlMonks FAQ
and Create a new user.

New Questions
 Perl, Android web app, AJAX, JSON 1 direct reply — Read more / Contribute by monx663 on Nov 20, 2017 at 17:49 Hi all This is not a 100% Perl question but I am Perl programmer and my question touches on Perl heavily. There is a fully functional web based CMS that is written in Perl for which I would like to make certain functionality available to an Android app being written. The requirements are not that "heavy". The Android App needs to do the following few things: * Send a username/password combination to gain access to the CMS backoffice. * Call certain URLs which will enable the app to get a list of objects (images,names, other table contents) available in the CMS's database. * Probably POST to certain URLs in order to be able to upload images and create content. My question is: What methodology/APIs should I be looking at to complete this Perl CMS/Android app "integration". I was thinking of writing an AJAX layer that would expose certain methods to the Android app, which will be calling them via HTTP requests. I was also thinking of modifying certain of the CMS's packages to perhaps implement methods for JSON based communication of textual and binary data (images). I have also heard of Mojolistic, which supposedly is intended for writing RESTful APIs but find this a bit of an overkill for my scenario. Does anybody want to offer any of his thoughts about which route to pursue? Extracting embedded file from PDF No replies — Read more | Post response by staszeko on Nov 20, 2017 at 17:36 I need to extract XML file embedded in PDF. I looked into module 'CAM::PDF' by Chris Dolan, but I could not find suitable examples. I need to do the extraction as part of a larger Perl program, without calls to third party tools like 'pdfdetach' or 'pdftk'. I would much appreciate any suggestion that could help me to achieve this task. Below is fragment of dictionary, returned by method 'getRootDict()'; you can see the name of XML file referenced there: $VAR1 = { 'Type' => bless( { 'gennum' => 0, 'value' => 'Catalog', 'type' => 'label', 'objnum' => 83 }, 'CAM::PDF::Node' ), 'Names' => bless( { 'gennum' => 0, 'value' => { 'EmbeddedFiles' => bless( { + 'gennum' => 0, + 'value' => { + 'Names' => bless( { + 'gennum' => 0, + 'value' => [ + bless( { + 'gennum' => 0 +, + 'value' => 'Z +UGFeRD-invoice.xml', + 'type' => 'st +ring', + 'objnum' => 8 +3 + }, 'CAM::PDF::N +ode' ), [download] hashref with(out) arrays 4 direct replies — Read more / Contribute by bfdi533 on Nov 20, 2017 at 17:36 I have some XML that is being returned from a REST API and sometimes there is a single result and sometime there are multiple results. I am having a hard time determining how to get the data that I need and know if there is an array or not. Example: $item->{result}->[0]->{value} $item->{result}->[1]->{value} [download] versus $item->{result}->{value} [download] I really need to get the value if there is one or know there are more than one value so I can collect them into an array. What is the best practice for this sort of thing? Perl an array of sockets 2 direct replies — Read more / Contribute by suhijo on Nov 20, 2017 at 13:42 I have two problems, first I need to open a websocket and register each socket into a struct so when an event from Asterisk AMI occurs, send some message to each one of the connected sockets from my @users array but when I open the socket and send the message the connection close. Second problem is I cannot receive data after websocket is open, a javascript code sends a simple string and I don't know how to open it, instead I receive html headers if I print $data inside sub incoming. Something I must be doing wrong. I have tried using other libraries, like Net::WebSocket::Server or Net::WebSocket::EV but doesn't suit me well, first one never return after start and second have no idea how to catch the ip, port, etc. Here is the code, it is a test, not fancy or anything just testing if the solution is possible use IO::Socket; use EV; use Data::Dumper; use Asterisk::AMI; use Digest::SHA1 qw(sha1 sha1_hex sha1_base64); use Encode qw(decode encode); use threads; use threads::shared; use warnings;$| = 1; my $connection_count = 0; my$h; my $fh; our @users : shared; my$astman = Asterisk::AMI->new(PeerAddr => '127.0.0.1', PeerPort => '5038', Username => 'admin', Secret => 'emel1t0', Events => 'on', Handlers => { default => \&eventhandler } ); die "Unable to connect to asterisk" unless ($astman); sub eventhandler { my ($ami, $event) = @_; if($event->{'Event'} eq "Dial"){ if($event->{'SubEvent'} eq "Begin"){ print "inicio,$event->{'CallerIDNum'},$event->{'Connect +edLineName'},$event->{'UniqueID'}\n"; buscar_exten(10000); } if($event->{'SubEvent'} eq "End"){ print "Fin,$event->{'UniqueID'},$event->{'DialStatus'}\ +n"; } } } my$server = new IO::Socket::INET(LocalPort => 50080, Type => SOCK_STR +EAM,Listen => SOMAXCONN, Reuse => 1, Proto => 'tcp'); my $w = EV::io$server, EV::READ, \&incoming; EV::loop; sub incoming { my $w=shift;$fh=$w->fh->accept or die; my$fileno = fileno $fh; push (@users,$fileno); my $cladd=$fh->peerhost(); my $clport=$fh->peerport(); my $claddr=$fh->peeraddr(); print "cladd: $cladd clport :$clport claddr:\n"; printf "$cladd: new socket connection #%d (%d)\n", ++$connection +_count, +scalar keys %$h;$fh->recv($data, 1024);$data =~ /Sec-WebSocket-Key: (\S+)/; $str =$1; print "key is1 $str|\n"; my$str = sha1_base64($str . "258EAFA5-E914-47DA-95CA-C5AB0D +C85B11"); send($fh, qq{HTTP/1.1 101 Switching Protocols\r\nConnection: + Upgrade\r\nUpgrade: websocket\r\nSec-Websocket-Accept: $str=\r\n\r\n +}, 0);$h->{$fh} = EV::io$fh, EV::READ, \&cliente; } sub cliente { my $c=shift; my$fh2=$c->fh; my$bytes_read=sysread($fh2, my$bytes, 9_999_999); return if (not exists $h->{$fh}); if (($bytes eq 'q') || ($bytes_read == 0)) { close($fh2); undef$c; delete $h->{$fh2}; printf "socket connection terminated by %s (%d (%d) sockets ++remaining)\n", $bytes_read == 0 ? 'peer' : 'server', --$connection_c +ount, scalar keys %$h; } } sub buscar_exten{$exten=$_[0]; print "buscando si <$exten> esta logueada-\n"; foreach my $b (@users) { open my$c, ">&=$b" ; send($c,"mandando mensaje 1000\r\n",0); } print "}\n"; } [download] cpan client problem with strawberry portable 1 direct reply — Read more / Contribute by Discipulus on Nov 20, 2017 at 07:46 Hello monks and nuns, before submitting a bug to the wonderful people who maintain strawberry perl I ask here just in case i missed something obvious.. The fact hitting me is that I cant get cpan client to report correctly modules versions installed. about cpanminus option I know cpan is not the only client to access CPAN and cpanm is the preferred solution for many of us, but it seems it has some issues (even if distributed along the portable edition!) because of paths expressed à la unix and some other strangness like cpanm --self-upgrade failing. the problem with cpan client Working with freshly downloaded and unzipped strawberry version and launching the portableshell.bat that come with each strawberry portable edition, and working, for example, with SDL module I have the following: ---------------------------------------------- Welcome to Strawberry Perl Portable Edition! * URL - http://www.strawberryperl.com/ * see README.TXT for more info ---------------------------------------------- Perl executable: C:\right\path\strawberry-perl-5.26.0.2-64bit-portable +BIS\perl\bin\perl.exe Perl version : 5.26.0 / MSWin32-x64-multi-thread cpan> r SDL .. All modules are up to date for SDL [download] But with the non interactive call (I suppose it's the same program anyway): cpan -D SDL SDL ---------------------------------------------------------------------- +--- (no description) F/FR/FROGGS/SDL-2.546.tar.gz (no installation file) Installed: not installed CPAN: 2.546 Not up to date Tobias Leich (FROGGS) froggs@cpan.org [download] All configuarations ( reviewed with o conf ) relative to working dirs ( build_dir cpan_home histfile keep_source_where make make_install_make_command patch prefs_dir ) are correct; absolute paths pointing to the current running version. Also @INC is correct for every portable distribution with strawberry prepended to it. The same for the PATH environment variable. This happens with versions: strawberry-perl-5.26.1.1-32bit-portable  strawberry-perl-5.26.0.2-64bit-portable strawberry-perl-5.24.2.1-64bit-portable strawberry-perl-5.22.3.1-64bit-portable strawberry-perl-5.20.3.3-64bit-portable Also happens: cpan> r Not_Existing_Module .. All modules are up to date for Not_Existing_Module [download] What can I do? I missing something very simple? Thanks for the attention. L* There are no rules, there are no thumbs.. Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS. where is whatsnew or changes in strawberry perl package 2 direct replies — Read more / Contribute by toohoo on Nov 20, 2017 at 06:59 Hello dear PerlMonks I'm searching for a whatsnew.txt or changes.txt for a concrete perl version in the downloaded package (portable version). I guess I only do oversee something. May someone please point me a hint? bes regards and thanks in advance, Thomas Overriding Global Variables 5 direct replies — Read more / Contribute by Mano_Man on Nov 19, 2017 at 08:41 Hi Monks, I'm looking for a way to have identical global variables in every package, and a single module that utilizes the data from them Example: package my_first; use Debug; # Imports in sub debug our $DEBUG_FLAG =1; debug("Print me"); #prints: Print me 1; package my_second; use Debug; our$DEBUG_FLAG =0; debug("Print me"); #prints none 1; package Debug; our $DEBUG_FLAG =0; #Default value sub debug($) { if(DEBUG_FLAG){ say $_[0]; } } 1; [download] Hope this is clear, appreciate any help.Looking for smart suggestions, better ways to do this (not OOP wise), and any other tidbit you can think of. Mixing OR with conditional operator 3 direct replies — Read more / Contribute by jockel on Nov 19, 2017 at 05:12 Hi Can someone please explain this behavior. I was surprised with result of the following code. (And please help me come up with a better Title for this question) I think the variable$test should be set to $val1 (1) but instead it gets set to$val2 (undef) #/usr/bin/perl use strict; my $test;$test = 1 || (undef && undef != 0) ? undef : 0; print "test = $test\n"; [download] OUTPUT: test = [download] -----BEGIN PERL GEEK CODE BLOCK----- Version: 0.01 P++>*$c--->---P6 > R >++++$M+>+++$O+++>+++$MA->+++$E > PU->++BD->-C+>+$D+>+$S->+++X >+WP >+++MO!PP n?CO--PO!>!(!)o?G!A--OLC--OLCC--OLJ--Ee !Ev-Eon-uL++>*uB!uS!uH-uo!w->!m+ ------END PERL GEEK CODE BLOCK------ Parsing DXF files for dimensional information 3 direct replies — Read more / Contribute by talexb on Nov 17, 2017 at 13:29 It pains me that I know little about this area of technology, but I guess it's not possible to know everything. A colleague has a bunch of AutoCAD files that have to do with urban planning, and he wants to extract the following information from the equivalent DXF files: Each corner point of each building lot with a latitude & longitude. Note that the lat. & long. may not be embedded in the file, but I am assuming the points are referred to on a relative scale so that they could be translated into lat & long data The colour of each corner point (this is relevant information, added by the planner) The area of each building lot - I believe that AutoCAD is calculating this. I have had a look at CPAN and haven't really found anything that will help me. My research on DXF tells me that it's a very low-level file, so I'm guessing that the information required may not even be available in the DXF file. If some monks have comments, thoughts, suggestions about where to begin, I'd appreciate it. Thanks! Alex / talexb / Toronto Thanks PJ. We owe you so much. Groklaw -- RIP -- 2003 to 2013. Need a second set of eyes: Very odd failure 5 direct replies — Read more / Contribute by blue_cowdawg on Nov 17, 2017 at 11:57 I must be missing something here so I'm asking for more eyes on something. I built a fairly simple straightforward module here and yet it is failing to work. This module does curls to an API (The Foreman) to extract some data from it. Nothing fancy here.... Here are the most important bits: package NCS::PuppetDB::Data; use 5.010000; use strict; use warnings; use JSON; our $curl="/usr/bin/curl -G 'http://localhost:8080/v3"; our$VERSION = '0.5.2'; sub new { my $self={}; bless$self,"NCS::PupptDB::Data"; return $self; } sub getHosts { my$self = shift; my $cmd=sprintf("%s/nodes 2>/dev/null",$curl); my $json = JSON->new->allow_nonref; my$jsonData=$cmd; my$decoded = $json->decode($jsonData); my $retval=[]; for my$entry(@$decoded){ push @$retval,$entry->{name}; } return sort$retval; } sub getHostFacts { my $self = shift; my$host = shift; my $cmd=sprintf("%s/nodes/%s/facts' 2>/dev/null",$curl,$host); my$json = JSON->new->allow_nonref; my $jsonData=$cmd; my $decoded =$json->decode($jsonData); my$retval = {}; for my $fact(@$decoded){ $retval->{$fact->{name}} = $fact->{value}; } return$retval; } sub getFact { my ($self,$host,$factname)=@_; my$facts=getHostFacts($host); return$facts->{$factname}; } 1; [download] The one and only script using it (so far) is complaining: Can't locate object method "getHosts" via package "NCS::PupptDB::Data" [download] What am I missing? Peter L. Berghold -- Unix Professional Peter -at- Berghold -dot- Net; Blog: http://blog.berghold.net Warning: No political correctness allowed. How can increase number sequence in a variable 4 direct replies — Read more / Contribute by yyy on Nov 17, 2017 at 11:15 Hi everyone, I have a few arrays naming @A_1, @A_2, @A_3.... I want to do a loop to for them, e.g. for(my$i =0; $i<10;$i++) { $A_$i[0] = 1234; ........ } I know $A_$i doesn't work. My question is how can I put $i into the array variable to make the sequence$A_1[0]=1234, \$A_2[0]=1234,....... Thanks Removing a test script from perl source 2 direct replies — Read more / Contribute by syphilis on Nov 17, 2017 at 06:59 Hi, This question relates to a transient, ongoing problem that I have running 'make test' when building perl from source on Windows using mingw-w64 64-bit ports of gcc. (Never any such problem with the mingw-w64 32-bit ports of gcc.) In a nutshell, I often (but not always, depending upon the version of gcc) strike the problem that an IO-Compress test script will hang during 'make test'. My only means of escape from this hang (AFAIK) is to hit Ctrl-C, which kills the entire 'make test' process - meaning that none of the other ensuing tests are run. Currently, the offender is cpan/IO-Compress/t/105oneshot-rawdeflate.t when building 64-bit blead. No problem with 'make test' when blead is built using 64-bit gcc-7.1.0, but that script hangs when blead is built with 64-bit gcc-7.2.0. My question: How do I re-arrange the source so that 'make test' will skip cpan/IO-Compress/t/105oneshot-rawdeflate.t, and yet run all of the other test scripts ? I should add that AFAICS there's really no problem with either the actual hanging test script, or the perl that has been built. These hangs only ever occur when running the script under 'make test'. Cheers,Rob
New Meditations
Antiquitates - liber I - In memoriam Robert M. Pirsig
5 direct replies — Read more / Contribute
by Discipulus
on Nov 15, 2017 at 04:16

## Antiquitates - liber I - In memoriam Robert M. Pirsig

### Introduction

This mediation is meant as the first of a short serie about antiquitates: good ancient things, knowledge. The central point of this is to focus on figures and ideas, or better pictures and schemas, that we have in our heads. This Pantheon is something we never speak about but is central in our approach to problems.

Infact while in our past (i'm speaking of the western colture) this pantheon were very homogeneous (geographically speaking but also between distinct social classes) in the current, global and postmodern world is something very variegated and fragmented and almost each one has a pantheon on his own.

Another point of this serie will be the importance of ancient wisdom. I totally disagree with the concept of human progress. I'm not speaking, obviously, of material conditions, but I believe the deepness reacheable by human thoughts has not improved over centuries. Only elements we play with have changed. Our fathers already discussed many still actual questions, useful also for us as programmers. I start here with an example in the near past, just to be kind with you, but other meditations will go far backward in time.

In an era while the organisation of production is even more constrained into fixed binaries, where new methodologies are put in the field to force us to act in a precomputed manner, where technologies too reorganize themselves to be impersonal, becomes even more important to focus on which immaterial bricks are worth to be collected to build the unique construction of our creativity as programmers.

### Pirsig's Chautauquas

Pirsig's recent death pushed me to ponder again about the importance of his discourse for my life and for my Perl programming activity. Pirsig is the author of the book Zen and the Art of Motorcycle Maintenance that I read many lives ago but which never disappeared from the background of my mind. Two central concepts still remain from his book as two rocks after thousand years of erosion.

### Quality

The first one is quality. Quality, if memory deserves, was what caused the protagonist's brain short circuit as filosophy professor. The research of quality and implicitly his definition, is something central in our lives. Ok but what this can be related to Perl and to programing? Is not maintainability just an aspect of quality? Readability over a clever jumble of hacks is not just another face of this concept? And why we prefer, well we love, Perl if not for a matter of overall quality? Quality of the programmer's activity while coding, not constrained by the interpreter's laws to double sign with blood the laguage way to code. Quality of the produced code in all it's phases: imagination, drawing, realizing, improving, testing and maintaining.

Quality is everyday something less. As the programmer hired after he told the interviewer he was able to cut ten lines of code each day. Quality is polishing the diamond.

But quality cannot be teach. We, well you, can show some incarnation of it. You can cast some light from your own quality and draw a beautiful picture on the white wall of ignorance. You cannot show directly the source of these rays, just the projection. Why? because quality is not a place but a path, a neverending one. Is a driving tension.

### Underlying form

The second concept is underlying form. This is crucial concept for the programmer. We solve problems. Solutions must be aware of underlying forms. Problems are occurences of the reality in the platonic world of ideas and forms and even if such abstract world does not exists, it heavily concurs in our understanding and approaching of problems.

Without the perception of something in the background our solution can just be a mere workaround or a color patch. A valid solution to a given, complex problem, can born only from the understanding of underlying forms.

Here the discourse becomes even more actual. We are living in the end of the firts Internet generation. Most of us have born in a totally analogic world and will die, as late as possible, in a totally different world. What about the next generation? Who knows? An anecdote, inspired by real life, can show different aproaches to the same problem.

### Generational anecdote

Tizio and Caio are both of the first internet generation. They share the usage of computer at home. Tizio, for fun, put an entry in the file HOSTS for the Caio's preffered website pointing to 127.0.0.1

Some hours after Caio points his browser to the preferred website and he notices a connection error. He then issues a ping to the website name and sees it strangely resolves to localhost. He wonders a bit if the provider has blocked the website so he issues an nslookup to the website domain name and he is happy to see that nslookup returns a valid public IP address. He points the browser to this address and he sees his preferred website again. So he realizes the problem must be at level of local name resolution. He opens the HOSTS file and comment the incriminated entry, adding some bad words addressed to Tizio.

Tizio make the same funny pun in a computer shared with Sempronio, a millennial second internet generation. Sempronio notices the error then tries some other websites and they are ok. Sempronio starts thinking that something is broken within the browser and he installs another browser but, with his big disappoint, the problem persists.
So he opens the Bag Of All Answers website and searches for "preferred_website blocked" and he discovers a plethora of causes that can make a website to be blocked. He reads superficially a bunch of articles without invastigating why governments block websites. After three minutes he modifies the search: "preferred_website blocked solution" and he happily discovers that some software can circumvent the problem.
So he installs a program named after the sligthly modified name of an ancient god, let say Marz. Sempronio does not know but this geeky program uses it's own nameservers and redistributes web requests over it's own network in a peer2peer way, Sempronio just complains it's a bit slow but finally the preferred website shows correctly again in the browser.
So for him it is a happy end (not saying that an international agency intercepts all Marz's traffic and programtically breaks all computers using it, but this is whole another story..).

With the above i dont mean all young people are stupid and all older ones are wise and spot everytime the rigth solution. I dont mean this at all. Just I want to highlight that if you know the underlying form of a web request probably you'll arrive to correct conclusions if experiencing some weird browsing behaviour.

### Conclusions

Quoting from Pirsig's book: Although motorcycle riding is romantic, motorcycle maintenance is purely classic. Author's work is full of examples of what he called classical and romantic types. I think such dichotomy is even too much stressed. I'm more in favor of the Humanistic Being, even as programmer. I dont want to be just another thooth in the gear not even knowing if I'm part of a clock or of a motorcycle. Knowing the big picture and to perceive underlying forms can make us better programmers.
An old book by a philosofy professor is worth to read, probably even better to have in the books shelf than an aseptic manual of programing methodology.

Roma 2770 AB URBE CONDITA / 8644 September 1993

L*

There are no rules, there are no thumbs..
Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.

Create A New User
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (5)
As of 2017-11-21 04:49 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
In order to be able to say "I know Perl", you must have:

Results (295 votes). Check out past polls.

Notices?