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
How can I have a Dancer2 before hook return an HTTP error?
2 direct replies — Read more / Contribute
by lembark
on Jan 24, 2025 at 20:40

    Q: What can I use in a Dancer2 before hook to cause the request being processed to hand back an HTTP error?

    Say I have a before hook that will filter out requests which are not worth processing. I would like to short-circuit the request and simply return, say, a 404. I've tried variations on bare return, returning a Dancer2::Core::Error object or the result of calling ->throw on one with no luck. I can abort with a 'die' but that leaves me returning a 500, not a 404 whatever. There is documentation in Dancer2 on handling errors generated by Dancer2 itself, but I cannot find anything that describes how to raise an error/exception/whatever from the Perl code running in handlers. The simplest example I can think of is a lightweight handler that rejects botched requests based on IP, username, etc, that are blacklisted.

    hook before => sub { ... is_bogus_request $request and ... # what??? };
Basic questions of Tk programming
4 direct replies — Read more / Contribute
by jmClifford
on Jan 23, 2025 at 05:45

    Hi. I got some code from this site that demonstrates "-textvariable" usage. However, there are some basic questions I have about it's operation. The code is;

    #!/usr/bin/perl use strict; use warnings; use Tk; use POSIX; my $red; my $green; my $blue; my $mw = MainWindow->new; $mw->geometry('300x100'); # x amount then y amount $mw->title('Raw Renamer'); # A frame for labels on the left hand size my $left_frame = $mw->Frame (-borderwidth => 2, -relief => 'groove') ->pack(-side => 'left', -anchor => 'n', -expand => 1); my $text_label = $left_frame->Label->pack(-side => 'left', # Why + this ? -anchor => 'n', -expand => 1); $text_label->Label(-text =>"Red")->pack( -side => 'top', -anchor => 'w'); $text_label->Label(-text =>"Green")->pack(-side => 'top', -anchor => 'w'); $text_label->Label(-text =>"Blue")->pack( -side => 'top', -anchor => 'w'); # Another frame for the ($red $green $blue) variables my $variable_frame = $mw->Frame (-borderwidth => 4, -relief => 'groove +') ->pack(-side => 'left', -anchor => 'n', -expand => 1); my $red_label = $variable_frame->Label(-textvariable =>\$red) ->pac +k(-side => 'top'); my $green_label = $variable_frame->Label(-textvariable =>\$green)->pac +k(-side => 'top'); my $blue_label = $variable_frame->Label(-textvariable =>\$blue) ->pac +k(-side => 'top'); Intialize(); # How is this infinite loop bypassed ? MainLoop; sub Intialize { print "Str"; while(1) { print "."; $red = floor(50*rand()); $red_label->update; sleep 2; $green = floor(50*rand()+50); $green_label->update; sleep 2; $blue = floor(50*rand()+100); $blue_label->update; sleep 2; } }

    The line "my $text_label" seems to be half a declaration that is used in an anonymous fashion in the subsequent 3 labels. Is this the case ?. I tried removing the "pack" part expecting that this is not required. But it is required.

    Next, the call "Intialize();" should get stuck in an infinite loop. But it does not and the program runs OK? and the "MainLoop;" gives a display screen.

    Regard JC.......

cpan, local mini-mirror, and urllist - can it be made to work?
1 direct reply — Read more / Contribute
by Intrepid
on Jan 22, 2025 at 15:35

    Hi Monks. I have built a minicpan on a Gnu/Linux box and now I am struggling with getting cpan (so far, not trying cpanminus or cpanplus) to find and query my local repository. I have a feeling based on SuperSearch and Google, that this has been discussed often, and I ask the esteemed Monks for their forbearance.

    My minicpan is rooted at /var/mirrors/minicpan and I am not clear on whether to push file:///var/mirrors/minicpan or file:///var/mirrors/minicpan/sources into urllist. I am also not sure whether there should be 3 slashes after file: or only two.I've tried every combination of these variable things and nothing works. One node, Offline cpan used by strawberry perl seem to indicate that 3 slashes are needed. There is also a discussion over at StackOverflow that inconclusively debates what the pushy_https configure parameter does.

    When I write "nothing works" I mean that this happens:

    cpan18> install Net::HTTP::Tiny
    Warning: Cannot install Net::HTTP::Tiny, don't know what it is.
    Try the command
    i /Net::HTTP::Tiny/
    to find objects with matching identifiers.

    This is always the result. I know the packages I want are in my minicpan. Any help would be appreciated.

    Jan 22, 2025 at 20:33 UTC

    A just machine to make big decisions
    Programmed by fellows (and gals) with compassion and vision
    We'll be clean when their work is done
    We'll be eternally free yes, and eternally young
    Donald Fagen -> I.G.Y.
    (Slightly modified for inclusiveness)

Indent XML data
2 direct replies — Read more / Contribute
by LexPl
on Jan 22, 2025 at 10:34

    Is there an easy way to indent an unindented XML file?

    Of course, significant whitespace between two adjacent elements or in mixed content should not be obscured or lost

    The data have an encoding ISO-8859-1 and contain tons of XML entities defined in a DTD with external entity declarations in a subdirectory

    sample input
    <?xml version="1.0" encoding="ISO-8859-1"?><root><para><pnum>1</pnum><ptext>This is a sample of a very specific text <emph>called</emph> <term>description</term> which has 2 subtypes: <list><item><term>1.</term><p>precise</p></item><item><term>2.</term><p>fuzzy</p></item></list></ptext></para></root>

    The output should look like this:

    <?xml version="1.0" encoding="ISO-8859-1"?> <root> <para> <pnum>1</pnum> <ptext>This is a sample of a very specific text <emph>called</ +emph> <term>description</term> which has 2 subtypes: <list> <item> <term>1.</term> <p>precise</p> </item> <item> <term>2.</term> <p>fuzzy</p> </item> </list> </ptext> </para> </root>
issue using NET::LDAP with load balancer dns alias with multiple ldap servers
1 direct reply — Read more / Contribute
by Anonymous Monk
on Jan 22, 2025 at 05:46

    Originally posted as a comment under Problem using NET::LDAP with multiple ldap servers

    I am running into this issue when I use a load balancer dns alias which has multiple ldap servers. It's not possible to input all of the individual ldap servers in the subroutine. Is there any other solution to this issue?

    here is my code:

    my $ldap = Net::LDAP->new( $host, port => $port, version => 3 ) or die + "$@";
    where $host in a load balancer.

    If I hard code one of the ldap server in the same code, it works!
    eg:

    my $ldap = Net::LDAP->new( 'myldap.server.com', port => $port, version + => 3 ) or die "$@";
Perl Tk module; optional select to result presentation
3 direct replies — Read more / Contribute
by jmClifford
on Jan 22, 2025 at 03:02

    Hi (again). I am using the Tk module with a Checkbutton routine as follows;

    # Set up frames to contain all the pids (for selection) my $frame_pids; $frame_pids = $main->Frame(-borderwidth => 2, -relief => 'groove'); my @sortedKeys = ( sort keys %IdxToNickName ); for my $k (@sortedKeys) { my $pid_nickname = $IdxToNickName{$k}; my $cb = $frame_pids->Checkbutton( -text => sprintf("%-15s",$pid_nickname), # courier and -15 implies fixed length left justifi +ed -variable => \$IdxToNickNameSel{$k}, # this is a hash for the selection result (so other +s can access) -font => ['courier', 10, 'bold'] # and a font size ); $IdxToNickNameSel{$k} = 0; # Initialise the selection to 0 $cb->pack(-side => 'top'); # Pack the cb according to left c +riteria }

    This permits me to have the checkbutton selections reference by the whole of the program (using "-variable"). For my next step I would like to selectively product the results and load into a hash which in turn is reflected onto the screen. What is the best way to achieve this output ??

    I expect the "-variable" option needs to be available, this this does not seem to be available for Text and Labels.

    Regards JC......

string containing characters
5 direct replies — Read more / Contribute
by IvanH
on Jan 21, 2025 at 01:07
    Can you suggest code to determine whether a string contains all of a list of characters in any order? Thanks.
PDL slice 2D array
3 direct replies — Read more / Contribute
by paul92
on Jan 18, 2025 at 10:44

    I'm trying to get a slice of a 2D PDL array and am having problems finding good examples of this. What I am trying to do is take Tick data and create create a OHLCV array based on a summarization of x number seconds. Any help would be apreciated. My code is below

    #!/usr/bin/env perl use strict; use warnings; use PDL; use PDL::NiceSlice; use Time::Local; # Sample tick data: array of arrays [timestamp, price, volume] # Example: ["2025-01-12 09:30:00", 100.5, 200] my $tick_data = [ ["2025-01-12 09:30:00", 100.5, 200], ["2025-01-12 09:30:15", 101.0, 150], ["2025-01-12 09:30:30", 100.8, 100], ["2025-01-12 09:30:45", 101.2, 300], ["2025-01-12 09:31:00", 101.0, 250], ]; # Group data into OHLCV intervals (e.g., 1 minute) my $interval_seconds = 20; # Set interval in seconds # Helper: Convert timestamp to epoch sub timestamp_to_epoch { my ($timestamp) = @_; my ($date, $time) = split(' ', $timestamp); my ($year, $month, $day) = split('-', $date); my ($hour, $min, $sec) = split(':', $time); return timelocal($sec, $min, $hour, $day, $month - 1, $year); } # Pre-process: Add epoch to data my $data = pdl([ map { my $epoch = timestamp_to_epoch($_->[0]); [$epoch, $_->[1], $_->[2]] } @$tick_data ]); for my $i (0..$data->dim(1)-1) { my $ts = $data->at(0,$i); my $p = $data->at(1,$i); my $v = $data->at(2,$i); } # Find unique interval buckets my $start_epoch = $data((0), 0); my $intervals = floor(($data(0, -1) - $start_epoch) / $interval_seco +nds); # Compute OHLCV my ($open, $high, $low, $close, $volume) = ([], [], [], [], []); for my $i (0 .. max($intervals)) { my $group = $data->where(floor(($data - $start_epoch) / $interval_ +seconds)== $i); next if $group->nelem == 0; # Skip empty groups # push @$open, $group(0, 1); # First price # push @$high, max($group(:, 1)); # push @$low, min($group(:, 1)); # push @$close, $group((($group->dim(0) - 1)), 1); # Last price # push @$volume, sum($group(:, 2)); } # Convert OHLCV to PDL for display #my $ohlcv = pdl($open, $high, $low, $close, $volume)->transpose; # Output results #print "OHLCV Format (Open, High, Low, Close, Volume):\n"; #print $ohlcv;
dereferencing question
4 direct replies — Read more / Contribute
by sectokia
on Jan 17, 2025 at 00:23

    Hi monks, Given anonymous structures like:

    my $array = [qw(a b c)]; my $hash = { a => 1, b => 2, c => 3 };

    Is there a technical reason so many people/books use:

    print $array->[2]; print $hash->{a};

    Instead of saving 1 character and using:

    print @$array[2]; print %$hash{a};
Prima: How to get a "table" layout?
5 direct replies — Read more / Contribute
by haj
on Jan 16, 2025 at 18:26

    Hello monks,

    In a Prima application I would like to define a widget which allows to set a bunch of configuration variables. So I have several lines, each consisting of a Prima::Label describing the entry and a Prima::InputLine where users can enter their values.

    Is there a decent way to get the InputLine widgets aligned vertically, like in a HTML table?

    Counting pixels and specifing the size attribute for the widgets works, sort of, but might break if the text in the Label widgets isn't known in advance, for example when it is pulled from some I18N framework. I would also prefer not to count pixels for the line height, which might differ for different platforms (or fonts).

    Any idea or pointer to a code example is welcome!


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, details, 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, summary, 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.