Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

The Monastery Gates

by gods
on Mar 23, 1999 at 10:47 UTC ( #131=superdoc: print w/replies, xml ) Need Help??

Donations gladly accepted

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

New Questions
GUI Design/Organization - Recommended Practices?
2 direct replies — Read more / Contribute
by atcroft
on Sep 23, 2016 at 15:26

    Are there currently any recommended common or "best" practices when creating a GUI for a script? (In terms of organization, etc.?)

Are these Perl Textbooks Good?
7 direct replies — Read more / Contribute
by Svetlana
on Sep 23, 2016 at 14:44
    Hello New to the forum. Have a simple question. I going to make an effort and learn Perl. I tend toward using text books rather than the internet. Are these books any good? I'm aware you have to be careful as some books/websites teach bad practices. Learning Perl 6th Edition(ISBN: 1449303587) Intermediate Perl(ISBN: 1449393098) Mastering Perl(ISBN: 144939311X) It's a series teaching Perl. Perl is now at 5.24, but the book covers 5.14. Is there that much of a difference? Would purchasing the book be a bad choice?
Problem using POE::Wheel::ReadWrite with pipes.
1 direct reply — Read more / Contribute
by ombibulous
on Sep 23, 2016 at 10:20

    Hello,

    I'm playing with a toy POE program that implements two sessions connected by a pipe that should simply cat an inupt file. Something like this:

    +- read side of pipe / ---------- ---------- STDIN --> | reader | -pipe-> | writer | --> STDOUT ---------- ---------- \ +- write side of pipe

    I started by using rcaputo's example that he posted here at perlmonks.org/?node_id=949005 and came up with this non-working code:

    use strict; use warnings; use IO::Pipely qw(pipely); use POE qw(Wheel::ReadWrite); my ($read_pipe, $write_pipe) = pipely(); # reader sends output to the write pipe my $reader = POE::Session->create( args => [ $write_pipe ], inline_states => { _start => sub { $_[HEAP]->{wheel} = POE::Wheel::ReadWrite->new( InputHandle => \*STDIN, OutputHandle => $_[ARG0], InputEvent => 'got_input', ErrorEvent => 'got_input_error', ); }, got_input => \&handle_input, got_input_error => \&handle_input_error, process_next_input => \&process_next_input, } ); # writer reads input from the read pipe my $writer = POE::Session->create( args => [$read_pipe], inline_states => { _start => sub { $_[HEAP]->{wheel} = POE::Wheel::ReadWrite->new( InputHandle => $_[ARG0], OutputHandle => \*STDOUT, InputEvent => 'got_input', ErrorEvent => 'got_input_error', ); }, got_input => \&handle_input, got_input_error => \&handle_input_error, process_next_input => \&process_next_input, } ); POE::Kernel->run(); exit; sub handle_input { my ( $kernel, $heap, $input ) = @_[KERNEL, HEAP, ARG0]; print $heap->{wheel}->put( $input ); $heap->{wheel}->flush(); $heap->{wheel}->pause_input(); $kernel->yield( 'process_next_input' ); } sub handle_input_error { my ($kernel, $heap) = @_[KERNEL, HEAP]; $kernel->yield( 'process_next_input' ); delete $heap->{wheel}; } sub process_next_input { my ($kernel, $heap) = @_[KERNEL, HEAP]; $heap->{wheel}->resume_input() if $heap->{wheel}; }

    On my Mac using Perl 5.20 I get this as the output when I feed the program a three line CSV file:

    ombibulous> perl cat.pl < test.csv 00001,2,3,4 0a,b,c,d 0foo,bar,baz ^C ombibulous>

    The ^C is me yanking the rope on my hung program. The lines should not begin with '0's, I don't know how they are creeping in.

    I thought (hoped) that after the $reader's handle_input() subroutine does a put(), pauses_input(), and yield(), then POE would see that there is an input for the $writer session and call its input handler. WRONG! I'm not getting how one session cedes processing to another session. I've seen the examples using posts() but I'm trying pipes instead. Can anyone tell me what I'm doing wrong?

    Eventually I'd like to build up a chain of sessions, connected by pipes, where each session does a particular transformation on input data; e.g., reader -> parser -> writer. I've already done this with a single process, parsing and writing within a read loop, and subprocesses, forked process for each step. I'd like to see how it works using POE. Is POE::Wheel::ReadWrite the best package to use if I'm going to use a single process?

    Thanks for any help, insights, and/or solutions.

Simple question about sleep function
7 direct replies — Read more / Contribute
by Lucas Rey
on Sep 23, 2016 at 06:29
    Dear community, this is a very simple question, but I cannot found reply.

    Which is the differences between:

    sleep (1);

    and

    select(undef, undef, undef, 1);

    It seems both stop the execution for 1 second. But, is there a real differences for example in term of performance?

    Thank you. Lucas

Implementing methods in a subclass or providing in-place callback: Is it overengineered?
2 direct replies — Read more / Contribute
by Dallaylaen
on Sep 23, 2016 at 05:12

    Hello, dear esteemed monks!

    I just wrote the following in my module. The idea is as follows: allow user to override default methods by either subclassing, or providing a callback. So a subclass with do_foo method and an instance of base class with on_foo member will behave exactly the same.

    However, looking at this again, I suspect it's being overengineered. Should I just provide default do_foo methods in subclass that search for a callback and croak if none found? This will still allow for both ad-hoc overriding and subclassing.

    Should I just go with normal OO and leave do_foo() alone?

    Guess there's no single correct answer after all, but I'd like to hear your opinions and make up my own.

    sub backend_call { my $self = shift; my $method = shift; my $todo = $self->{"on_$method"} || $self->can("do_$method"); if (!$todo) { my $sub = [caller(1)]->[3]; $sub =~ s/.*:://; croak join "", (ref $self || $self),"->",$sub, ": no backend found for $method"; }; return $todo->($self, @_); };

    Thank you!

Can't get a server response from LWP Request
2 direct replies — Read more / Contribute
by ddominnik
on Sep 23, 2016 at 03:45

    First off, regarding Perl and coding in general I have just started to learn so it would be great if you could give me easy to understand/execute answers. Now onto the real problem:

    I'm trying to create a tool for a JIRA server at my workplace. But I can't seem to get a response from the server. I already struggle with the login, which takes a JSON string as a POST request and sends back a JSON string with cookie information. I've tried through the browser and with JavaScript, that somehow works, but Perl gives me a 500 status code response. I've already tried JIRA::REST


    use JIRA::REST; use JSON; my $jira = JIRA::REST->new('https://jira.hostname:PORT/jira', 'myuser' +, 'mypass'); my $request = $jira->POST("/issue/search", undef, { jql=> 'project ~ MYPROJECT and status = closed', starAt=> 0, maxResults=>1, fields=>[asignee], }); print(parse_json ($request));

    Then I tried REST::Client

    use REST::Client; my $client = REST::Client->new(); $client->setHost('https://jira.hostname:PORT/jira/rest'); $client->request('post', '/auth/1/session', ['{ "username" : "myus +er", "password" : "mypass" }', undef]); print ($client->responseContent());

    And now I'm trying a custom request with LWP

    use LWP; use LWP::UserAgent; use HTTP::Request; use JSON; my $host = 'https://jira.hostname:PORT/jira/rest'; my $loginurl = '/auth/1/session'; my %credentials = ("username"=>"myuser", "password"=>"mypa +ss"); my $json = encode_json \%credentials; my $request = HTTP::Request->new('POST', $host.=$loginurl) +; $request -> header('Content-Type'=>'application/json'); $request -> content($json); my $browser = LWP::UserAgent->new; $browser -> agent('Mozilla/5.0'); $browser -> protocols_allowed(['https']); my $response = $browser->request($request); if($response->is_success){ print $response->decoded_content; } else { die $response->status_line; };

    All of them are giving me the same or a similar response:

    500 Can't connect to jira.hostname:PORT Bad file descriptor at C:/myperl/perl/vendor/lib/LWP/Protocol/http.pm +line 47. at jiratest.pl line 28.

    I think that the LWP lib might be broken somehow, but I already tried upgrading and reinstalling via CPAN and still got no response. The code from the LWP/Protocol/http.pm file is:

    sub _new_socket { my($self, $host, $port, $timeout) = @_; # IPv6 literal IP address should be [bracketed] to remove # ambiguity between ip address and port number. if ( ($host =~ /:/) && ($host !~ /^\[/) ) { $host = "[$host]"; } local($^W) = 0; # IO::Socket::INET can be noisy my $sock = $self->socket_class->new(PeerAddr => $host, PeerPort => $port, LocalAddr => $self->{ua}{local_address}, Proto => 'tcp', Timeout => $timeout, KeepAlive => !!$self->{ua}{conn_cache}, SendTE => 1, $self->_extra_sock_opts($host, $port), ); unless ($sock) { # IO::Socket::INET leaves additional error messages in $@ my $status = "Can't connect to $host:$port"; if ($@ =~ /\bconnect: (.*)/ || $@ =~ /\b(Bad hostname)\b/ || $@ =~ /\b(certificate verify failed)\b/ || $@ =~ /\b(Crypt-SSLeay can't verify hostnames)\b/ ) { $status .= " ($1)"; } die "$status\n\n$@"; # this is the mentioned "line 47" } # perl 5.005's IO::Socket does not have the blocking method. eval { $sock->blocking(0); }; $sock; }

    I really hoped I could fix this myself as generally solving issues yourself is a great way to learn about the language, but I really don't know what to do anymore. It has to be a problem on the client side, because the server is responding as regular when I'm using JavaScript. Any help would be greatly appreciated!
    P.S: I've always used  use strict; use warnings; as well, so I don't think it has something to do with that


    EDIT: Corion's comment was right, it was a proxy issue as well as a SSL-Certificate issue.

    Thank you for your help Perl Monks!

Need script help
3 direct replies — Read more / Contribute
by jmckinzie
on Sep 22, 2016 at 13:05
    I have a command whose syntax is:  wspmvdata -s $srv -P sp:$src -t  \@$line -P tp: @ep1 @ep2 I can have as many @servers as I want as long as they fit in a command line (ie limitation) Can you help me figure out how to do this? This is what I have so far.
    #!/usr/bin/perl $pm="word.pm"; $srv=srv; $src="D:/Tivoli/bin/lcf_bundle.43100/bin/w32-ix86/inv/SCAN/"; $dst="C:/wansupp"; $file=binfile; $tmpfile="D:/Tivoli/custom/bin/binfile.txt"; $cmd="wspmvdata -s $srv -P sp:$src -t \@$line -P tp: $file"; ## this works but I want to shorten the list to a few test endpoints #@eplist=split(/\n/, `wlsendpts \@P1.pm | grep End | grep -v tcp3 | gr +ep reg`); @eplist=(1_reg1, 2_reg1, 3_reg1); open(DATA, "<$tmpfile") or die "Can't open data"; @eplist = <DATA>; close (DATA); }
    I basically want to run the one command with @ep,@ep2,@ep3
How to set pipe first and then use the forkmanager?
3 direct replies — Read more / Contribute
by mlin
on Sep 22, 2016 at 05:03
    While I'm trying to the ForkManager to do the parallel tasks. I find that I should pass the N data files to program A using a pipe. The form is like this:
    open $h, "| program_A" or die ...; foreach (@data_files) { print $h ...; print $h ...; ... } close($h);
    If I want to deal with these files parallelly, like using 4 processors, I think I must establish 4 pipes first(right?), then how to tell the perl to use these pipes automatically? I'm a little confused about the progress. Could you please tell me some schemes to solve this problem and give me some explanation? Thanks a lot! ----- complement: If while the program A runs, it usually print some information or warnings to the screen? Will it be a trouble for the forked processes? or I must throw the output of A, like:
    foreach (@data_files) { open $h, "| program_A 2>& /dev/null" or die ...; print $h ...; print $h ...; ... } close($h);
Limit Socket (throttle) to send specific ammount of packets every second
2 direct replies — Read more / Contribute
by Lucas Rey
on Sep 22, 2016 at 01:58
    Dear Community, I'm programming a simple script in perl that do the following:
    1) Open a socket to a specific server 2) Reads data line by line from a big file using a while loop 3) Send data using the open socket
    I don't report the whole code since it works perfect and could be too long. What I need to accomplish is send an ammount of packets every seconds. For example I would like to limit (throttle) to send 100 packets per second. What I need, is understand how (and if) I can implement this kind of mechanism, or simply an idea. The actual code looks like:
    Open Socket Open file containing data to send while # Read file line by line { Send data to Server }
    Thank you, Lucas.
Testing a library that accesses an Oracle Database
3 direct replies — Read more / Contribute
by docdurdee
on Sep 21, 2016 at 23:21
    Hello Monks, I'm writing tests for a program that accesses an Oracle database. When I run the tests directly or using prove, the tests work wonderfully. When I build the distribution (using Dist::Zilla) and run tests from the generated makefile, they fail: Could not connect to ... : install_driver(Oracle) failed: Can't load ... Library not loaded: @rpath/libclntsh.dylib.12.1 It must be an environment issue (I'm running OS X), but I have not been able to crack it via the usual endless googling. I think there may be some way to get the appropriate variables set via Dist::Zilla using the D::Z::P::MakeMaker::Awesome, but I shelved that effort in favor of hacking something that works at all to begin with. I tried setting the Oracle %ENV variables (dumped from my local environment where it works) within the problematic test using a BEGIN block, but still no luck...
    BEGIN { $ENV{ORACLE_HOME}="somepathto/oracle"; $ENV{DYLD_LIBRARY_PATH}="somepathto/oracle/lib"; }
    Any ideas? Thanks! UPDATE: I also tried unsetting the environment variables from within the test that works when I run it directly:
    BEGIN{ `export DYLD_LIBRARY_PATH=""`; `export ORACLE_HOME=""`; `export LD_LIBRARY_PATH=""`; $ENV{DYLD_LIBRARY_PATH}=''; $ENV{ORACLE_HOME}='' $ENV{LD_LIBRARY_PATH}=''; }
    The test still works!!!! I'm only able to make the test crash during the "make test" phase. This is curious...
How to parse and modify a XML file ?
3 direct replies — Read more / Contribute
by ankit.tayal560
on Sep 21, 2016 at 02:22

    What is the basic difference between XML::libXML and XML::DOM modules? I want to parse a XML file(in my case : very large XML file) and do certain modifications to its elements. which one should I use?

Day of week calculation
4 direct replies — Read more / Contribute
by reisinge
on Sep 21, 2016 at 01:58

    Hello guys. Can someone explain to me how would one come up with the idea behind the code from line 12 to 18? I mean I kind of understand it but I would have never though of it :-). (It's from Intermediate Perl book, by the way).

    1 #!perl 2 use strict; 3 use warnings; 4 use utf8; 5 use File::Find; 6 use Time::Local; 7 my $target_dow = 1; # Sunday is 0, Monday is 1, ... 8 my @starting_directories = ("."); 9 my $seconds_per_day = 24 * 60 * 60; 10 my($sec, $min, $hour, $day, $mon, $yr, $dow) = localtime; 11 my $start = timelocal(0, 0, 0, $day, $mon, $yr); # midn +ight today 12 while ($dow != $target_dow) { 13 # Back up one day 14 $start -= $seconds_per_day; # hope no DST! :-) 15 if (--$dow < 0) { 16 $dow += 7; 17 } 18 } 19 my $stop = $start + $seconds_per_day; 20 my($gather, $yield) = gather_mtime_between($start, $stop); 21 find($gather, @starting_directories); 22 my @files = $yield->( ); 23 for my $file (@files) { 24 my $mtime = (stat $file)[9]; # mtime via slice 25 my $when = localtime $mtime; 26 print "$when: $file\n"; 27 }
    I have never taken any courses in computer science or software engineering. -- esr (http://www.catb.org/~esr/resume.html)
New Cool Uses for Perl
extract (a range of) numbered lines from a file
4 direct replies — Read more / Contribute
by shmem
on Sep 19, 2016 at 16:49

    Ever wanted to get a range of lines extracted from some file? Easy: load into editor, highlight lines, copy (usually Ctrl<c>), go to target, paste (usually Ctrl<v>).

    You want to do that from the command line? With UNIX/Linux you have some options, combining the output of wc -l with head and tail.
    You could also combine sed and awk (TIMTOWTDI applies):

    sed -e '10,15p;4p;s/.*//' file | awk '!/^$/{print $0}' somefile

    I'm not aware of Windows tools to do this task.
    But anyways, this is unwieldy, specially if you want to read piped input into your editor of choice calling an external command.
    Perl to the rescue:

    #!/usr/bin/perl -n my $usage; BEGIN { $usage = "usage: $0 linespec file\n" . "linespec example: 2,5,32-42,4\n" . "this extracts lines 2,4,5 and 32 to 42 from file\n"; $spec=shift; die $usage unless $spec; @l=split/,/,$spec; for(@l){ ($s,$e)=split/-/; $e||=$s; $_=[$s,$e]; } } CHECK { unless(@ARGV) { push @ARGV, <DATA>; chomp @ARGV; } die $usage unless @ARGV; $file = $ARGV[0]; } # === loop ==== for $l(@l){ print if $.>=$l->[0] and $.<=$l->[1] } # === end === # END { if ($file) { open $fh,'<', $0; @lines = <$fh>; close $fh; open $fh,'>',$0; for(@lines){ print $fh $_; last if /^__DATA__$/; } print $fh $file,"\n"; } } __DATA__

    Above script, concisely named l (or e.g. lines if that one-letter identifier is already taken) and stored somewhere in any of your private $PATH locations, allows you to e.g. in vi

    : r ! l 11-13,42,125-234 somefile

    and have the specified lines from somefile read into your current buffer after the line of your cursor.
    To do the same with emacs, ask LanX, he knows the proper Ctrl-Shift-Meta-Alt-X encantations to do so.
    This code is self-modifying: it places the filename it is invoked upon after the __DATA__ token, so if you want to include more lines of the same file, it suffices to say

    : r ! l 1234-1500

    For that reason this piece of cr.. code is strictly personal and not suitable to be installed system-wide.

    perl -le'print map{pack c,($-++?1:13)+ord}split//,ESEL'
Log In?
Username:
Password:

What's my password?
Create A New User
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (2)
As of 2016-09-25 01:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Extraterrestrials haven't visited the Earth yet because:







    Results (462 votes). Check out past polls.