Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Seekers of Perl Wisdom

by gods
on Sep 07, 1999 at 20:28 UTC ( #479=superdoc: print w/replies, xml ) Need Help??

If you have a question on how to do something in Perl, or you need a Perl solution to an actual real-life problem, or you're unsure why something you've tried just isn't working... then this section is the place to ask. Post a new question!

However, you might consider asking in the chatterbox first (if you're a registered user). The response time tends to be quicker, and if it turns out that the problem/solutions are too much for the cb to handle, the kind monks will be sure to direct you here.

User Questions
Async timed events with Dancer2
1 direct reply — Read more / Contribute
by stevieb
on Sep 24, 2016 at 19:03

    I'm still working on my Dancer2 application, but now I'm at the point where I need it to periodically, even without client interaction. Essentially, I want the Dancer2 app to behave like a normal always-running background script while a client browser is not attached.

    So, what I need to do is have this app periodically do something without tying up the main application. I wrote a *very* basic async timed event module Async::Event::Interval (yeah, for fun, mostly). It works, and does what I need it to do (the event is a forked process). Here's an example:

    use warnings; use strict; use Async::Event::Interval; my $event = Async::Event::Interval->new( 1, # interval, in seconds sub { print "event...\n"; }, ); $event->start; sleep 1; # wait for first event to fire print "main is going to sleep...\n"; sleep 5; print "done\n";

    Output:

    event... main is going to sleep... event... event... event... event... event... done

    I fetch the PID of the event process, and it shows up just dandy as running in the proc list:

    $ ps ax | grep 22834 22834 pts/2 S+ 0:00 perl t/evt.pl

    However, no matter where it is I create and start the event in a Dancer2 app, it fires after the first interval is expired, but then in the proc list I see:

    $ps ax | grep 22732 22732 pts/2 Z+ 0:00 [/home/spek/repo] <defunct>

    Can anyone explain what Dancer2 is doing that forces a child process to become defunct, or how I can get around/avoid this problem without having to have a second background app running to do the side-work that is needed? If anyone thinks a different async type software will work, I'll ditch my own, as it was just for playing around anyways.

    As a side note, I have no idea why it's showing /home/spek/repo in the proc entry, as my current working dir is ~/repo/app-envui when I start the webapp.

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 fall1.pl 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 fall1.pl #!/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?

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

Check connection state prior to send data
1 direct reply — Read more / Contribute
by Lucas Rey
on Sep 24, 2016 at 01:23
    Dear community, I'm programming a simple socket client who connect to a server and send data. The below code works perfect, but I'm searching a method to check connection prior to send data. This because I'm sending data continuosly using a loop, and if, for some reason, the connection goes down, the script hangs. So, is there a way to check if the connection is established and, if not, call again OpenSocket Sub inside the loop?
    #!/usr/bin/perl use IO::Socket; my $sock1; sub OpenSocket{ $sock1 = new IO::Socket::INET( PeerAddr => '192.168.10.7', PeerPort => 8000, Proto => 'tcp'); $sock1 or die "no socket :$!"; } ################ START SCRIPT ################# OpenSocket(); $str="Something to send"; while (1) { $sock1->send($str); } close($sock1);
perl excel writer xlsx
2 direct replies — Read more / Contribute
by gengtian
on Sep 23, 2016 at 19:44
    I got this simplest script to test whether I can use perl to make excel file. Under windows 10 bash environment, it will only create a 471 byetes file and the Excel can't open it. Then I put the same script on a Fedora12 computer and it works. Because I am going to use perl to generate an excel file with about 200000 rows, I really want to it to work on the windows 10 machine because the fedora machine is way too slow. Thanks.
    #!/usr/bin/perl use strict; use Excel::Writer::XLSX; my $workbook = Excel::Writer::XLSX->new( 'simple.xlsx' ); my $worksheet = $workbook->add_worksheet(); $worksheet->write( 0, 0, 'Hi Excel!' );
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?
Help installing USB
3 direct replies — Read more / Contribute
by dJJackson
on Sep 23, 2016 at 14:10
    Platform: Raspberry II

    sudo cpan install Inline::C ran fine

    But when I run: sudo cpan install Device::USB I the following errors:

    Reading '/root/.cpan/Metadata' Database was generated on Fri, 23 Sep 2016 15:17:02 GMT Running install for module 'Device::USB' Checksum for /root/.cpan/sources/authors/id/G/GW/GWADEJ/Device-USB-0.36.tar.gz ok 'YAML' not installed, will not store persistent state Configuring G/GW/GWADEJ/Device-USB-0.36.tar.gz with Makefile.PL Checking if your kit is complete... Looks good Generating a Unix-style Makefile Writing Makefile for Device::USB Writing MYMETA.yml and MYMETA.json Failed to find module path for 'USB.pm' at Makefile.PL line 50. Warning: No success on command/usr/bin/perl Makefile.PL INSTALLDIRS=site GWADEJ/Device-USB-0.36.tar.gz /usr/bin/perl Makefile.PL INSTALLDIRS=site -- NOT OK

unzip fail using IO::Uncompress::Unzip
3 direct replies — Read more / Contribute
by keienn
on Sep 23, 2016 at 12:27

    Great Monks! I am trying to unzip some .txt files using IO::Uncompress::Unzip in the code snippet below. Am getting this error though, which i suspect is to do with unseen folders in windows;
    .
    Use of uninitialized value $_1 in string eq at C:/Strawberry/perl/lib/IO/Compress/Base/Common.pm line 280. unzip failed: input file '.' is a directory

    Below is the code

    opendir(ZIPPED, $zipdir)or die "couldn't open $zipdir: $!\n"; my @zd = readdir(ZIPPED); my @uzd; foreach(@zd) { my $inf = $_; my $outf = $uzd[@uzd]; # print $_,"\n"; unzip $inf => $outf or die "unzip failed: $UnzipError\n"; }

    Below is sample of the output i get if i run the print line and comment out the unzip line;
    .
    ..
    730372_Atoll.zip
    730376V01_Atoll.zip
    730378V01_Atoll.zip
    730691_Atoll.zip
    732689_Atoll.zip
    732690_Atoll.zip
    732691_Atoll.zip
    How can i get past the "." and ".." and get unzip to uncompress the files. Thanks!

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

    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.


Add your question
Title:
Your question:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":


  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.
  • 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 surveying the Monastery: (4)
    As of 2016-09-25 09:21 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?
      Extraterrestrials haven't visited the Earth yet because:







      Results (468 votes). Check out past polls.