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

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
shared array while use ForkManager
1 direct reply — Read more / Contribute
by mlin
on Sep 25, 2016 at 05:21
    Hi all,

    I am writing a script using fork to speed up my process of N files. It works well now. However, I need output information pushed in an array in my serial process, which will be used later. Will there be some conflict while I use fork? It looks like this:
    foreach my $i (@group) { $pm->start and next; foreach my $term (@$i) { warn "No such file. - $term\n" and next if ! -e $term; ... $IsGood = ...; our @quality; push @quality $IsGood; } $pm->finish; } $pm->wait_all_children;
calculate length of day as function of space at onset of fall
2 direct replies — Read more / Contribute
by Datz_cozee75
on Sep 24, 2016 at 03:20

    Hello Monks,

    When did fall begin? Is there only one answer to that question? I'm honestly not sure. Let me describe the scene in terms of the dynamics of gilligan's island, because if we can't generalize to the arbitrary location in the pacific, then this isn't much of a script. 'MaryAnn' and I found ourselves on an island with a west wind coming in that made it hard to stand. It was 9/11, and our phones were gone. The Gilligan in me savors being lost, but we were up against the elements, and knowing west was important. In such conditions, we hunkered down, stayed close, estimated waves, and watched events along the ecliptic.

    Several days after the ordeal, we're looking at the sunset, talking about the onset of fall, and this time with perl at hand...didn't want to donate my computer to the Columbia. I looked at the sky maps and realized that fall occurs exactly when the sun sets in the west. Maryann's question was "how long was the day today?" I'd like to be informed by my compiler. Output precedes code.

    C:\Users\Fred\Desktop>perl cos tau = - tan phi * tan delta onset of fall ==> delta equal zero delta is 0 phi is latitude: 45 in portland (close enough) phi is 0.785398163397448 rhs is 0 tau is 1.5707963267949 degrees is 90
    C:\Users\Fred\Desktop>type #!/usr/bin/perl -w use strict; use 5.010; use Math::Trig; use Math::Trig ':pi'; say "cos tau = - tan phi * tan delta"; say "onset of fall ==> delta equal zero"; my $delta = tan( 0); say "delta is $delta"; say "phi is latitude: 45 in portland (close enough)"; my $phi = deg2rad(45); say "phi is $phi"; my $rhs = - tan ($phi) * tan ($delta); say "rhs is $rhs"; my $tau = acos($rhs); say "tau is $tau"; my $degrees = rad2deg($tau); say "degrees is $degrees";

    I'm given to believe that the output in degrees is a measurement of time. I've read two differing treatments on how it is *exactly* so, both of which differ, and are wrong. The better one gets to 1.3%. That's not good enough for an oblate spheroid, unless I can't come up with better. What's more, the entire scenario makes me think of re-creating giant wheels, and history is replete with able people who have been making this a thing for much longer than I have.

    My question is: when did fall hit you?

    Счастливая осень!

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?
How to disable:Odd number of elements in hash assignment warning?
2 direct replies — Read more / Contribute
by BrowserUk
on Sep 23, 2016 at 12:04

    I'm splitting some data into a hash, and occasionally, the last value may be missing.

    This is known and unimportant, so I'd like to locally disable that warning; but what category to give to no warnings ...?

    (And for bonus points, how to find it?)

    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority". I knew I was on the right track :)
    In the absence of evidence, opinion is indistinguishable from prejudice.
Problem using POE::Wheel::ReadWrite with pipes.
2 direct replies — Read more / Contribute
by ombibulous
on Sep 23, 2016 at 10:20


    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 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 < 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.

Declaring and checking content of variables with consecutive names
2 direct replies — Read more / Contribute
by rflesch
on Sep 23, 2016 at 07:34
    Dear community,

    in a Perl CGI script, how can I
    (a) declare a set of 100 string variables $str0 .. $str99 in one loop in order to obtain

    my $str0=''; (..) my $str99='';

    (b) further down in the script, find out (in a loop) which of those are empty?

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);


    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/ +line 47. at 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/ 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=""; $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 \ | 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);
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?

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

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (5)
As of 2016-09-25 23:53 GMT
Find Nodes?
    Voting Booth?
    Extraterrestrials haven't visited the Earth yet because:

    Results (474 votes). Check out past polls.