Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number

Seekers of Perl Wisdom

( [id://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.

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.

Post a new question!

User Questions
callback function params
1 direct reply — Read more / Contribute
by azadian
on May 25, 2024 at 10:43
    I've written a fair amount of Perl back in the day, but nothing OO. Now I'm forced to use a callback, and don't have a clue how despite assorted research. Here's the code:
    sub itm { } my $db = SQLite::DB->new($DBfile); + $db->connect or croak "Can't connect to $DBfile, aborting\n"; + $db->select("select * from item where date = $date", \&itm) or croak " +Can't read items for '$date', aborting\n";
    Now I presume that somehow the data from the selected rows will be handed to my itm() callback function, but I don't know how. How can I access this data?
way of declare an integer variable instead use /^\d+$/
2 direct replies — Read more / Contribute
by vincentaxhe
on May 24, 2024 at 22:13

    just want apply some static type check such as int, I found 'use integer' is global and not flexible ,/^\d+$/ validation is wordy.

    such as $a attribute: int

Net::EPP fractional seconds
1 direct reply — Read more / Contribute
by HariSeldon
on May 22, 2024 at 11:31

    I'm using Net::EPP 0.27 'Info' command with Perl v5.38.2 to connect to the UK's Nominet servers to retrieve the exact creation date of any particular domain name.

    The Nominet specs and Nominet support say that the response should include the full creation timestamp including microseconds in a format such as:


    but my script shows the raw response as being:


    Note that Net::EPP shows me the time in BST and without the microseconds when the actual creation time is stored by Nominet as UTC/GMT. Can anyone shed any light on whether this is a limitation of Net::EPP or my script or is Nominet mistaken in what their server is responding with?

    #!/usr/bin/perl -w use Time::HiRes; use Net::EPP::Client; use Net::EPP::Frame::Command::Info::Domain; use Digest::MD5 qw(md5_hex); init_epp(); get_domain_info(""); sub get_domain_info { my($domain) = (@_); my $info = Net::EPP::Frame::Command::Info::Domain->new; eval { $info->setDomain($domain); $info->clTRID->appendText(md5_hex(Time::HiRes::time().$$)); print_xml($info->toString(1)); $answer = $epp->request($info); print_xml($answer->toString(1)); }; if ($@) { if (ref($@)) { die($@->print()); } else { die(($@)); } } } sub print_xml { my @lines = (@_); my ($result); foreach $line (@lines) { $line =~ s/></>\n</g; $result .= $line; } print "$result\n"; } sub init_epp { # passwords etc redacted my $greeting = $epp->connect(); my $login = Net::EPP::Frame::Command::Login->new; }
cpanm Tk build errors
3 direct replies — Read more / Contribute
by thimes
on May 21, 2024 at 20:19

    Installed Perlbrew on 2019 Macbook Pro (Intel core i9) 32GB RAM. MacOS Sonoma 14.4.1. Tested and works well. Tried to install Tk using cpanm Tk. Recieved ERRORS in build.log configure: error: installation or configuration problem: C compiler cannot create executables.

    Writing MYMETA.yml and MYMETA.json Building jpeg/libjpeg.a checking for gcc... cc checking whether the C compiler (cc -fno-common -DPERL_DARWIN -mmacosx +-version-min=14.4 -DNO_POSIX_2008_LOCALE -fno-strict-aliasing -pipe - +fstack-protector-strong -I/usr/local/include -fno-common -DPERL_DAR +WIN -mmacosx-version-min=14.4 -DNO_POSIX_2008_LOCALE -fno-strict-alia +sing -pipe -fstack-protector-strong -I/usr/local/include -mmacosx-ve +rsion-min=14.4 -fstack-protector-strong -L/usr/local/lib) works... no configure: error: installation or configuration problem: C compiler ca +nnot create executables. ERROR from evaluation of /Users/terryhimes/.cpanm/work/1716015046.9428 +1/Tk-804.036/JPEG/Makefile.PL: ERROR from evaluation of /Users/terryh +imes/.cpanm/work/1716015046.94281/Tk-804.036/JPEG/jpeg/Makefile.PL: E +rror opening Makefile: No such file or directory at ./Makefile.PL lin +e 41. at ./Makefile.PL line 41. require ./Makefile.PL called at /Users/terryhimes/perl5/perlbrew/p +erls/perl-5.38.2/lib/5.38.2/ExtUtils/ line 258 ExtUtils::MakeMaker::eval_in_x(PACK021=HASH(0x7fe6d883bef0), "/Use +rs/terryhimes/.cpanm/work/1716015046.94281/Tk-804.036/JPE"...) called + at /Users/terryhimes/perl5/perlbrew/perls/perl-5.38.2/lib/5.38.2/Ext +Utils/ line 245 eval {...} called at /Users/terryhimes/perl5/perlbrew/perls/perl-5 +.38.2/lib/5.38.2/ExtUtils/ line 245 ExtUtils::MakeMaker::eval_in_subdirs(PACK021=HASH(0x7fe6d883bef0)) + called at /Users/terryhimes/perl5/perlbrew/perls/perl-5.38.2/lib/5.3 +8.2/ExtUtils/ line 823 ExtUtils::MakeMaker::new("MM", PACK021=HASH(0x7fe6d883bef0)) calle +d at /Users/terryhimes/perl5/perlbrew/perls/perl-5.38.2/lib/5.38.2/Ex +tUtils/ line 78 ExtUtils::MakeMaker::WriteMakefile("VERSION", 804.036, "XS_VERSION +", 804.036, "DEFINE", "", "INC", "-I.. -Ijpeg -I/usr/X11R6/include -I +/opt/X11/include/freetype2", ...)
    I have installed Perlbrew on a new 2023 Macbook Pro, then Tk with no problems, works great. I followed the same instructions in both cases. Any ideas?

mojo app causes weird morbo loop that stops when app is loaded
2 direct replies — Read more / Contribute
by Anonymous Monk
on May 21, 2024 at 02:06
    What could cause a Mojolicious::Lite app started with morbo to continuously reload for no apparent reason, as if it was receiving requests, until it gets an actual request? For example, these 9 lines repeat over and over until the app is loaded in a browser, then it stops spewing these lines and works as expected:
    Web application available at GET "/" Routing to a callback 200 OK (0.204005s, 4.902/s) GET "/%3C!DOCTYPE%20html%3E%3Chead%3E ... Template "not_found.development.html.ep" not found Template "not_found.html.ep" not found Rendering template "mojo/debug.html.ep" Your secret passphrase needs to be changed (see FAQ for more) 404 Not Found (0.017273s, 57.894/s)
    That 4th line is somehow appending a string of html, which the app builds up and renders, to a get request. I have no idea how that's happening at all, let alone autonomously without loading it in a browser. This is an old working app with no known problems. After restarting morbo a few times all is well, and I can't reproduce it, but am curious if this is a known issue when someone like me does something stupid with the code? Thanks

    Tonight at 11...DOOOOOOOOOOOOOOOM!

Weird behavior of int()
6 direct replies — Read more / Contribute
by cLive ;-)
on May 20, 2024 at 16:49

    (posted this in the FB Perl group, but I know a lot of you aren't on Fb, so...

    Been writing perl since '95. Only found out today that this idiom for coercing a string into an int can fail:

    my $x = int($str+0);

    It fails when the string begins with nan or inf (case insensitive). So, running this:

    my @test = qw(in inf info information INF INFO Na Nan Nanny NAN NANNY +nan04); foreach my $x (@test) { my $y = int($x); printf "%11s -> %s\n", $x, $y; }


    in -> 0 inf -> Inf info -> Inf information -> Inf INF -> Inf INFO -> Inf Na -> 0 Nan -> NaN Nanny -> NaN NAN -> NaN NANNY -> NaN nan04 -> NaN

    It feels like a bug that the regex matches on /^(?:nan|inf).*/s (or \w* - I haven't fully tested it. Rather than matching on /^(?:nan|inf)$/s

    Just wondered if this actually is a bug. I've always used Math::BigFloat whenever I need accurate math, so I've never used NaN/Inf in code before.

    what do you all think?

NYTProf missing dot files
1 direct reply — Read more / Contribute
by Anonymous Monk
on May 20, 2024 at 13:01
    Devel::NYTProf only generates two graphviz dot files, linked from the main profile page. Each sub page in the profile has a link to "Call graph for these subroutines as a Graphviz dot language file" but the files don't exist. Does anyone know why these links are broken and how to enable them? Thank you
CGI::Carp sometimes fails
4 direct replies — Read more / Contribute
by Bod
on May 18, 2024 at 12:04

    I'm using the following code...

    #!/usr/bin/perl use CGI::Carp qw(fatalsToBrowser); use strict; use warnings; use lib ( "$ENV{'DOCUMENT_ROOT'}/../lib", "$ENV{'DOCUMENT_ROOT'}/../.. +/prod/lib" ); use Bod::CRM; use Site::Utils; die "X - " . $file{'receipt', 'file'};

    The variable $file{'receipt', 'file'} is defined using our and exported with Exporter in the private module Site::Utils.

    Different die statements give very different results
    die "here!"; - CGI::Carp works as expected
    die "X - " . $xxx; - CGI::Carp works as expected - global symbol $xxx requires...
    die "X - " . $file{'receipt', 'file'}; - CGI::Carp doesn't write anything to the browser - I just get a 500 error from the browser.

    How can this be?

exec() fails with strange message
1 direct reply — Read more / Contribute
by dissident
on May 17, 2024 at 16:37
    I am trying to make a function similar to system(), which collects stdin and stdout as well.
    I know that there are some modules with stuff like that.
    But the purpose of this is a) to learn and b) to have this simple task solved without big module.

    So I have a subroutine "system2" in the code below.
    It takes as argument a command line string, and other stuff.

    This subroutine "system2" gets called from the subroutine "main" at the end of the code.
    To test it, I am using a simple C program:

    #include <stdio.h> main() { fprintf(stdout,"This is output on stdout! \n"); fprintf(stderr,"This is output on stderr! \n"); sleep(10); return 0; }

    My Perl script described above is this:

    #!/usr/local/bin/perl use strict; use warnings; use POSIX ":sys_wait_h"; $|++; # away with buffering # stringref read_a_file( string filename) sub read_a_file { my $fn = shift; local $/ = undef; open FILE, $fn or return undef; my $text = <FILE>; close FILE or return undef; return \$text; } # int system2( string cmdline, # stringref retmsg, # stringref stdoutttxr, # stringref stderrtxr) sub system2 { my $er = shift; my $cmd = shift; my $stdouttxr = shift; my $stderrtxr = shift; my $retval; my $stdoutfn = '/tmp/teststdout'; my $stderrfn = '/tmp/teststderr'; unlink ($stdoutfn) if (-e $stdoutfn); unlink ($stderrfn) if (-e $stderrfn); my $pid = fork(); if ($pid < 0) { $$er .= "Forking failed with return code $pid."; return $pid; } elsif ($pid == 0) { # CHILD use POSIX qw(setsid); setsid() or die "Can't start a new session: $!"; chdir('/'); $SIG{HUP} = 'IGNORE'; umask 0033; close STDIN or die; close STDOUT or die; close STDERR or die; open(STDIN, '</dev/null') or die; open(STDOUT, ">$stdoutfn") or die; open(STDERR, ">$stderrfn") or die; my @argv = split(/ /, $cmd); exec( @argv); } my $wpid = waitpid($pid,0); my $normalexit = WIFEXITED(${^CHILD_ERROR_NATIVE}); if ($normalexit) { $retval = WEXITSTATUS(${^CHILD_ERROR_NATIVE}); } else { if (WIFSIGNALED(${^CHILD_ERROR_NATIVE})) { $$er .= "Child terminated due to signal"; if (WTERMSIG(${^CHILD_ERROR_NATIVE})) { $$er .= ": SIGTERM"; } } } if (-e $stdoutfn) { if (-s $stdoutfn) { my $s = read_a_file($stdoutfn); die if (not defined $s); $$$stdouttxr = $s; } unlink ($stdoutfn); } if (-e $stderrfn) { if (-s $stderrfn) { my $s = read_a_file($stderrfn); die if (not defined $s); $$$stderrtxr = $s; } unlink ($stderrfn); } return $retval; } sub main { my $er = ''; my $cmd = '/path_to_a_out/a.out'; my $stdouttxr = undef; my $stderrtxr = undef; my $ret = system2($cmd,\$er,\$stdouttxr,\$stderrtxr); if (defined $ret) { print "return value = '$ret'\n"; } else { print "return value = undef\n"; } if ($er ne '') { print "Error text: '$er'\n"; } else { print "No error text!\n"; } if (defined $stdouttxr) { print "STDOUT: '$$$stdouttxr'\n"; } else { print "No stdout output!\n"; } if (defined $stderrtxr) { print "STDERR: '$$$stderrtxr'\n"; } else { print "No stderr output!\n"; } return 0; } exit main();

    No matter whether I use '/path_to_a_out/a.out' or 'exec /path_to_a_out/a.out' as command string, the output is always this:

    % perl -w return value = '2' No error text! No stdout output! STDERR: 'sh: Syntax error: word unexpected (expecting ")") ' %

    This looks to me as if Perl gives something to sh, which the latter is unable to swallow.
    Any idea what am I doing wrong?

Problem with doubles results
2 direct replies — Read more / Contribute
by frank1
on May 17, 2024 at 13:47

    I have a problem with my script it doubles results to same json line. this is the output

    [ { "info": "\t\t\t\t\t\t \n<p>John UK Male</p> \n<p>Kieth UK Mal +e</p>" }, { "info": "\t\t\t\t\t\t \n<p>John UK Male</p> \n<p>Kieth UK Mal +e</p>" } ]
    my $sth = $dbh->prepare("SELECT name country gender FROM tbl_U WHERE l +ocation = ?"); $sth->execute('UK'); my $result = $sth->fetchall_arrayref(); my $json_msg; my %hash; my @updated_data; foreach my $result (@$result) { my ($name, $country, $gender) = @$result; $json_msg .= <<HTML; <p>$name $country $gender</p> HTML ; %hash = ( "info" => $json_msg); push( @updated_data, \%hash ); } my $json = encode_json \@updated_data; print $Cgi->header( -type => 'application/json' ),$json;

    results should be atleast

    [ { "info": "\t\t\t\t\t\t \n<p>John UK Male</p>" }, { "info": "\t\t\t\t\t\t \n<p>Kieth UK Male</p>" } ]

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

  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?

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

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (4)
As of 2024-05-25 22:40 GMT
Find Nodes?
    Voting Booth?

    No recent polls found