Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

The Monastery Gates

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

Quests
poll ideas quest 2020
Starts at: Jan 01, 2020 at 00:00
Ends at: Dec 31, 2020 at 23:59
Current Status: Active
5 replies by pollsters
    First, read How do I create a Poll?. Then suggest your poll here. Complete ideas are more likely to be used.

    Note that links may be used in choices but not in the title.

Supplications
AnyEvent tcp_server not working
2 direct replies — Read more / Contribute
by navalned
on Apr 03, 2020 at 17:34
    I have the following code that I believe should function as an echo server.
    #!/usr/bin/env perl use strict ; use warnings ; use AnyEvent ; use AnyEvent::Handle ; use AnyEvent::Socket ; my $main = AnyEvent->condvar(); tcp_server undef, undef, sub { my ($fh, $host, $port) = @_; my $handle; $handle = AnyEvent::Handle->new( fh => $fh, on_error => sub { my ($hdl, $fatal, $msg) = @_; AE::log error => $msg; $hdl->destroy(); }, on_eof => sub { my ($hdl) = @_; $hdl->destroy(); }, on_read => sub { my ($hdl) = @_; $hdl->push_read(line => sub { my ($hdl, $line) = @_; if ($line =~ m/quit/i) { $hdl->push_write("goodbye\n"); $hdl->destroy(); } $hdl->push_write($line); }); } ); $handle->push_write("Hello $host:$port\n"); }, sub { my ($fh, $thishost, $thisport) = @_; print STDERR "$thishost:$thisport\n"; }; $main->recv();
    However, when I netcat into the server. I see the greeting and the server immediately closes the connection. I'm probably missing something simple, but not sure what. Thanks!
DateTime issues
1 direct reply — Read more / Contribute
by htmanning
on Apr 03, 2020 at 16:49
    Monks, I'm using the following to check for things happening one year from now and one week from now.
    use DateTime::Duration (); my $one_year_from_now = $now->add( years=>1 ); if ($reservation_date > $one_year_from_now) { do something } and then use DateTime::Duration (); my $one_week_from_now = $now->add( weeks=>1 ); if ($reservation_date > $one_week_from_now) { do something }
    If the one year from now routine happens before the one week from now routine, it cancels out the one week from now routine. It is as if it is resetting NOW and I don't understand why.
Perl/Tk and exit(0)
4 direct replies — Read more / Contribute
by saw55
on Apr 02, 2020 at 18:55

    I have a several hundred line Perl/Tk program with a subroutine (timedDialog) that opens a window with a message such as “starting backup”, “creating tar file”, “finished”, etc. and then the window closes after a few seconds. This all works fine, but when I try to use this sub to display an “exiting” message after the user hits a cancel button the script exits before the message displays. This seems to be because of the “exit(0)” statement immediately following it—I tried putting “sleep 5” in between, but that didn’t help.

    The following demonstrates my problem. If the exit statement in sub checkDays is commented out the message is displayed, if it is uncommented you never see the message. Can someone please tell me what I am doing wrong?

    #!/usr/bin/perl ###################################################################### +## use strict; use warnings; use Tk; my $mw = MainWindow -> new; my $timedDialogTitle = ''; my $timedDialogText = ''; my $svBtn = undef; #Option window SAVE button. &setupGUI; $mw->deiconify(); $mw->raise(); MainLoop; exit(0); ################################################ ################################################ sub setupGUI{ $timedDialogTitle = "STARTING BACKUP"; $timedDialogText = "Backing up files..."; $svBtn = $mw->Button( -text => "SAVE", -command => sub {&checkDays +; &timedDialog($timedDialogTitle, $timedDialogText, 5_000);}); $svBtn->grid(-row => 9, -column => 2, -sticky => 'e'); $mw->bind('<KeyPress-Return>' => sub {&checkDays; &timedDialog($ti +medDialogTitle, $timedDialogText, 5_000);}); $mw-> withdraw(); } ##################################### sub checkDays { &timedDialog("Exiting", "O.K., no backup will be made, + then....Exiting", 5_000); exit(0); } ##################################### sub timedDialog { my $subwindow = MainWindow->new; $subwindow->geometry("490x150+400+400"); $subwindow->title($_[0]); my $label = $subwindow->Label(-text => $_[1]); $label->pack; $subwindow->after($_[2], sub {$subwindow->destroy;}); } #####################################
Perl seems to mistreat "PerlIO" environment variable (Windows)
1 direct reply — Read more / Contribute
by vr
on Apr 02, 2020 at 18:27

    Instead of poking inside source of some App::* CPAN distribution, I tried to fix app's binary STDOUT output (prevent lf to crlf conversion) using said variable, here's SSCCE:

    @echo off set PERLIO= perl -E "print qq(\n)" >> tmp perl -E "binmode STDOUT; print qq(\n)" >> tmp set PERLIO=:raw perl -E "print qq(\n)" >> tmp perl -E "binmode STDOUT; print qq(\n)" >> tmp set PERLIO=:raw:crlf:pop perl -E "print qq(\n)" >> tmp perl -E "binmode STDOUT; print qq(\n)" >> tmp perl -E "binmode STDOUT, ':crlf'; print qq(\n)" >> tmp set PERLIO= perl -Mopen=IO,raw -E "say unpack 'H*', $_ while <ARGV>" tmp del tmp

    output:

    0d0a 0a 0d0a 0d0a 0a 0a 0d0a

    Line 3 seems to indicate that

    The list becomes the default for all Perl's IO

    (quote from link above) doesn't work; line 4 is weird -- IO is now broken and unfixable; further lines demonstrate working and toggleable solution (including from the same perl line/script, not shown above), using strange sandwiches -- :raw:crlf:raw works, too. Looks like a bug to me, maybe not urgent (was it always there?), let it be documented, TWIMC.

Understanding Perl / Brew Perl and Cpan on macOS
2 direct replies — Read more / Contribute
by feumw
on Apr 02, 2020 at 05:36
    The title might be a little weird but I couldn't sum up better what I want to know.

    So I'm working on a macOS. As war as I know /usr/bin/perl is the default perl which comes with the OS. Some people say it's bad and you can't get full usage out of it so they prefer to install perl again via homebrew - The Missing Package Manager for macOS (or Linux).. No matter which perl (default=/usr/bin/perl / or homebrew=/usr/local/bin/perl is "active" for me cpan stays on the same location (/Users/myusername/.cpan). I double checked both with perl -MCPAN -e shell aswell.
    How does this work? Does cpan install the Modules into it's own directories and no matter which perl is active, perl is just allowed to access those folders?

    On Stackoverflow I found an article about cpan-vs-mcpan-perl saying:
    cpan installs for the perl in the shebang (#!) line of the cpan file.
    When someone has more than one perl installed on a machine, they sometimes run the wrong copy of cpan, and thus end up installing modules for the wrong instance of perl.
    One solution to that would be to specify the full path to the correct cpan file.
    perl -MCPAN -e shell is the other solution. It allows you to explicitly specify the install of perl for which you want the modules to be installed.
    I'd have assumed I have different locations using perl -MCPAN -e shell.

    Let's say I want to split my CPANs having one for the default and one for the homebrew perl. How can I do this?
    And does reinstalling a new fresh and clean cpan mean just rm -rf /Users/myusername/.cpan ?

    I hope I can find some Wisdom here to clear up my minds. Thanks in advice.
Test runner that acts like a test and can be run as one
4 direct replies — Read more / Contribute
by Your Mother
on Apr 02, 2020 at 00:10

    (Update: Solved to my satisfaction for this particular problem. New runner in comment below.)

    I have a big test that has quite a few configuration options and reasons to run subtests or not depending on environment. Works great but it cannot play well with the master runner because there are a couple hundred other tests that are mostly without the general environment concerns and none with the same granularity of configuration.

    I want to run the test with three (or more) configurations/environments. I can certainly just do that inside the test. It’s trivial. However! It’s already a huge test, I don’t know that my current permutations are final, it’s confusing enough already and another layer or two of indentation and wrapping all of the subtests… it might be trivial to write, it will not be fun to read or edit, and it won’t be as clean to exit, skip, rerun, run alone/once with a single set of the permutations as it is now…

    So… This is a summary of my DWIM first idea, but not something that actually does it –

    run.t.raw, the original test

    #!perl use strictures; use Test::More; subtest "Prod" => sub { plan skip_all => "Set PROD_TEST to run" unless $ENV{PROD_TEST}; ok 1, "OHAI, PROD!"; done_testing(1); }; subtest "Dev" => sub { plan skip_all => "Set DEV_TEST to run" unless $ENV{DEV_TEST}; ok 1, "OHAI, DEV!"; done_testing(1); }; done_testing(2);

    runner.t

    #!perl # File: runner.t use strictures; use App::Prove; for my $env (qw/ PROD DEV /) { my $test = join "_", $env, "TEST"; local $ENV{$test} = 1; my $app = App::Prove->new; $app->process_args( -I => "./", -v => "run.t.raw" ); eval { $app->run } or die "Failed... not proceeding: $@"; }

    Without runner / normal prove

    prove -v run.t.raw run.t.raw .. # Subtest: Prod 1..0 # SKIP Set PROD_TEST to run ok 1 # skip Set PROD_TEST to run # Subtest: Dev 1..0 # SKIP Set DEV_TEST to run ok 2 # skip Set DEV_TEST to run 1..2 ok All tests successful. Files=1, Tests=2, 0 wallclock secs ( 0.02 usr 0.01 sys + 0.06 cusr + 0.01 csys = 0.10 CPU) Result: PASS

    How it falls down / fails to DWIM

    prove runner.t runner.t .. All 2 subtests passed (less 2 skipped subtests: 0 okay) Test Summary Report ------------------- runner.t (Wstat: 0 Tests: 6 Failed: 4) Failed tests: 1-3, 6 Parse errors: Plan (1..2) must be at the beginning or end of the TAP + output Tests out of sequence. Found (1) but expected (4) Tests out of sequence. Found (2) but expected (5) More than one plan found in TAP output Bad plan. You planned 2 tests but ran 6. Files=1, Tests=6, 0 wallclock secs ( 0.01 usr 0.01 sys + 0.18 cusr + 0.05 csys = 0.25 CPU) Result: FAIL

    Sidenote, works perfectly but cannot be run with prove or in normal harness

    perl runner.t # … All tests successful.

    My question: How can I make the “runner” act like a single “master” test in a clean way? I may end up doing it in a messy way but I feel certain that I’m just missing some simple idea. I tried some do and straight eval stuff but without getting kind of complicated, it won’t do the right thing because it issues too many start/stop/count statements for the runner to accept it as one “master” test.

Counting days with DateTime
3 direct replies — Read more / Contribute
by htmanning
on Apr 01, 2020 at 14:51
    Monks, I'm doing a simple reservation system and using DateTime I can make sure the reservation is not before today.
    use DateTime; my $now = DateTime->now( time_zone => 'Pacific/Honolulu' ); my $reservation_date = DateTime->new( year => $CONFIG{'date_year'}, month => $CONFIG{'date_month'}, day => $CONFIG{'date_day'}, hour => $myhour, minute => $mymin, time_zone => 'Pacific/Honolulu', ); if ($reservation_date < $now) { print "error"; }
    But what I need now is to restrict future reservations to no more than 1 week ahead of time, but something like this doesn't work:
    } elsif ($reservation_date - $now > 7) { do something. }
    It seems I have to use the duration compare class, but I'm not sure how to do it when I'm only comparing the reservation date to now, and the base time to compare to is now.
"Segmentation fault" text not captured by perl script
1 direct reply — Read more / Contribute
by Special_K
on Apr 01, 2020 at 13:21

    I am debugging an issue with a compiled program written in c++ that is being called from a perl script. If I create a shell script that calls the compiled program directly:

    #!/bin/tcsh myexecutable exit

    And then run it, the last 2 lines written to the console are:

    right before out-of-bounds array access Segmentation fault

    If I instead write the following standalone perl script:

    #!/tool/bin/perl use strict; my $cmd = "myexecutable"; system($cmd); my $exit_value = $? >> 8; my $signal_num = $? & 127; my $dumped_core = $? & 128; printf("exit_value = $exit_value, signal_num = $signal_num, dumped_cor +e = $dumped_core\n");

    The last line printed from the executable is:

    right before out-of-bounds array access

    The values of the variables are as follows: exit_value = 0, signal_num = 11, dumped_core = 0 Why in this case is the "Segmentation fault" text not captured by the perl script? The behavior is the same if I replace this line:

    system($cmd);
    with this:
    my $backtick_return = `$cmd`;

    and then print $backtick_return at the end of the program. When I first started debugging this issue I was unaware of how to properly check system() return codes. Now that I've added that check as shown above debugging future issues should be easier, but I would still like to know why the "Segmentation fault" text isn't being captured by the system command, as seeing that when I first started debugging this issue would have been helpful.

Building ARRAY with grep expression NOT working
4 direct replies — Read more / Contribute
by denting24by7
on Mar 31, 2020 at 16:02

    I am doing something wrong trying to build an array that should contain all jscript extension file names. I am very new to perl. I have this working in bash. I know that the first array has the lines containing the jscript file names. Just can't figure out how to remove just them and put them in an array to sort unique items.

    #!/usr/bin/perl use strict; use warnings; sub main { my @js = (); my @ujs =(); my $file = 'access_log.txt'; open(FH, $file) or die("File $file not found"); while(my $String = <FH>) { if($String =~ '[^/]*\.js') { push(@js,($String)); #print "$String \n"; @ujs = grep {/[^/]*\.js/}, @js; # print @ujs; } } close(FH); foreach (@ujs) { print "$_\n"; } } main();
declaring lexical variables in shortest scope: performance?
9 direct replies — Read more / Contribute
by bliako
on Mar 31, 2020 at 06:22

    Hello lockdown ones,

    Everytime I declare a variable I believe a flop dies in my CPU. Probably because I fell in the C cauldron in my formative years. But now, and in Perl, the paradigm is to "lexicalise" variables within the innermost scope. For example, for:

    my $x; for $x (1,2,3){ print "x=$x\n" }

    perlcritic a.pl says Loop iterator is not lexical at line 6, column 1.  See page 108 of PBP.  (Severity: 5)

    But this pacifies perlcritic:

    for my $x (1,2,3){ print "x=$x\n" }

    But wakes in me primordial fears of will that variable be created 3 times and decrease performance? (for the sake of readability and, perhaps, stability and not introducing subtle bugs). Does anyone know the difference in performance between the two scripts? Even if it is tiny!

    bw, bliako

How install multiple version of perl
5 direct replies — Read more / Contribute
by maria80e
on Mar 31, 2020 at 03:04
    I have the following question in perl.

    1) Is it possible to install multiple version of perl(example perl version: 5.6 and perl version 5.24) in windows system.

    2) How to call the perl file using version. For example, call the new version perl file(5.24) from old version of perl file(5.6).

Grab username from WP Cookie
4 direct replies — Read more / Contribute
by htmanning
on Mar 31, 2020 at 00:45
    Monks,

    I don't know if this is possible, but I need to grab a Wordpress user's username from the cookie once they are logged in. I will pass that to another Perl based part of the site. There are 3 cookies with the username followed by some hash. I'm not having much luck finding a way to read it when I won't know the cookie name ahead of time. Any ideas?

Cool Uses for Perl
Applied MCE : Building a load-testing framework for PSGI apps with Plack::Test and MCE::Queue
No replies — Read more | Post response
by 1nickt
on Mar 30, 2020 at 10:49

    If you develop PSGI apps in Dancer2, Mojolicious, Plack or something else, you probably know that it's fairly easy to test all your routes and confirm that they function as expected. But what about the performance of your app under load? Will there be any bottlenecks? Can the database support the concurrent connections you plan to open? Do you have enough, or too many, workers serving requests? Etc.

    The following script shows how to build a load-testing framework for your PSGI app using Plack::Test for the scaffold and MCE::Flow and MCE::Queue to create the concurrent traffic. (The example includes a Dancer2 app to be exercised, but you can of course use your own app class from outside or inside the script, updating the test flow appropriately.)

    The demonstration simulates an API for managing account records that exposes three endpoints: / POST, / GET, / PUT. The workflow/account lifespan is typical: the caller first creates an account record via a POST call, which returns an id that must be used for future calls. The demonstration simulates the caller encountering the account record still with status 'pending' on the first GET call, and having to call again until it is activated. Finally, the caller deletes the account.

    The script is configured to create 1,000 accounts shared among 10 users. (Note that this is an example and includes no parameter checking, error handling, etc. For demonstration purposes only.) The example app creates an SQLite database on disk.

    How it works
    The script uses MCE::Flow to simulate the workflow, and MCE::Queue to manage the jobs. Two user subroutines are defined, one for the queue "producer" and one for the queue "consumers." The "producer" represents callers making the initial requests to create new accounts; these are placed onto the queue at small intervals. The "consumers" of the queue represent callers making subsequent requests to the app and reacting to the response, sometimes by making a new request. In that case a job for the new request is placed on the queue before the "consumer" finishes the current job.

    To tune the test, change the number of consumers, add more accounts to be created, or reduce/increase the sleeps representing work being performed and caller latency.

    To run the test
    Just copy the code, install the dependencies, and run. You may wish to tail the log file (by default at /tmp/test.log) to see what the app is doing. Afterwards you may wish to examine the populated database (by default at /tmp/test.sqlite), as it will be overwritten on the next run.



    script to load-test/profile a PSGI application


    Some sample output:


    The way forward always starts with a minimal test.
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 examining the Monastery: (6)
As of 2020-04-04 00:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    The most amusing oxymoron is:
















    Results (32 votes). Check out past polls.

    Notices?