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
remove chars with regex
5 direct replies — Read more / Contribute
by frank1
on Feb 26, 2025 at 04:09

    I need some help on removing the middle chars and leave the first 5 characters and last 5 characters using regex

    i want this output

    0x388c ... b19297

    but am getting this error Use of uninitialized value $_ in pattern match (m//)

    my $char = "0x388c818ca8b9251b393131c08a736a67ccb19297"; my($output) = $char = /^(?<=\S{5})\S(?=\S{7})/; print $output;
what should be in PERL5LIB after installing from source the 5.40.1 version on MacOS (am64)
1 direct reply — Read more / Contribute
by kwolcott
on Feb 21, 2025 at 23:28

    I'm really confused and frustrated about how to get my PERL5LIB environment variable set correctly.

    I'm on MacOS Sequoia, aarch64, running zsh, installed Perl 5.40.1 from source, into the /opt/perl_5.40.1 directory.

    I already have a Perl 5.38.2, also built from source, located in the /opt/perl directory.

    I have a MacPorts version of Perl installed (5.34.3). I removed an additional MacPorts Perl version 5.38.3 that I had installed recently.

    I was reading in the Programming Perl book about PERL5LIB...I don't understand the order of the paths that should be in the PERL5LIB.

    I've installed MANY Perl modules from CPAN using cpanm, specifying -L path respective to each version of Perl.

    I have a section in my ~/.zshrc for Perl that looks like this:

    I'm not using homebrew and I'm not using perlbrew.

    I was using Sidef (installing manually as a standalone executable, not as a Perl Module) for some while, then things went bonkers when I installed Perl 5.38.3 from MacPorts (I think). Now Sidef fails, and many Perl programs fail that require modules (some work, some fail).

    ./wagstaff_primes.pl Can't locate local/lib.pm in @INC (you may need to install the local:: +lib module) (@INC entries checked: /opt/perl_5.40.1/lib/site_perl/5.4 +0.1/darwin-2level /opt/perl_5.40.1/lib/site_perl/5.40.1 /opt/perl_5.4 +0.1/lib/5.40.1/darwin-2level /opt/perl_5.40.1/lib/5.40.1) at ./wagsta +ff_primes.pl line 4. BEGIN failed--compilation aborted at ./wagstaff_primes.pl line 4.

    The aforementioned is a script from Rosetta Code.

    find /opt/perl_5.40.1/lib -type f -name lib.pm /opt/perl_5.40.1/lib/5.40.1/darwin-2level/lib.pm /opt/perl_5.40.1/lib/lib/perl5/local/lib.pm
Existing module for PerlX::Maybe except for hash existence?
1 direct reply — Read more / Contribute
by Corion
on Feb 21, 2025 at 11:51

    I'm quite fond of using PerlX::Maybe to pass parameters to subroutines if they are there:

    GetOptions( 'f' => \my $filename, 'bar' => \my $bar, 'bruce' => \my $batman, 'u' => \my $universe, ); foo( file => $filename, maybe bar => $bar, maybe baz => $batman, maybe universe => $universe, )

    The above will invoke foo() with only the hash keys that have a defined value. This is better in the sense that this allows foo() to make a difference between parameter was not passed at all and parameter was passed, but was undef:

    sub foo( %options ) { if( ! exists $options{ baz } ) { $options{ baz } = 'Superman'; }; ... }

    Now, I'd like to have something similar(ish) to maybe on the receiving side for subroutines and objects, but I'm lacking a good name and a good syntax for it. The idea is to only set a value in a hash if the key does not exist yet. This is different from the // operator, because that one only checks for defined-ness, not for existence.

    If we already had full-grown subroutine keyword parameters, this could be written in a declarative way as:

    sub foo( :$baz = 'Superman', :$bar, :$file, :$universe='DC' ) { }

    (actually, I'm not sure if the above is correct for an invocation foo( baz => undef )).

    But we don't have named parameters in the syntax yet, so we have to deparse the parameters ourselves:

    sub foo( %options ) { ... }

    Let's assume that option is a good name for this (I'm not convinced):

    sub option ( $key, $def, $options ) { if( !exists $options->{ $key } ) { $options->{ $key } = $def; } return $options }

    Then we could have a syntax like this:

    sub foo( %options ) { option baz => 'Superman', option universe => 'DC', \%options; return \%options }

    But I'm not entirely happy with this approach for two reasons:

    1. It doesn't strike me as overly elegant. I'm happy with it being not overly elegant, but there are some warts:
      • We pass in and modify the %options hash by reference. Alternatively we could do %options = option foo => 'bar', %options;, but that copies the whole hash a lot of times
      • We eagerly evaluate the default values, which might be costly in the case of function calls:
        option files => [glob('~/*')], option html => $user_agent->get('https://example.com'),
    2. There must be something like this on CPAN already

    Test file:

Adding XMP metadata in a pdf
3 direct replies — Read more / Contribute
by srikrishnan
on Feb 21, 2025 at 10:23

    Hi All,

    I want to add XMP metadata and set Initial view in the existing pdf. For that i have tried PDF::API2 and other such modules, but i am helpless.

    In existing PDF, i have Bookmarks, Tags, hyperlinks, internal links, Annotation popups, Text insertion icons, everything. When i try to add XMP metadata in my pdf, everything got disappeared from my output pdf.

    Is there any module or option to achieve my requirement by retaining all the existing features in my input pdf?

    regards,

    Srikrishnan

AppVeyor failing to build/test CPAN distro
1 direct reply — Read more / Contribute
by jkeenan1
on Feb 20, 2025 at 22:09
    I am doing my annual revision and upload of an income-tax-related CPAN module. For testing on Windows (to which I myself don't have access), this year I added an AppVeyor configuration file (.appveyor.yml) essentially cloned from one of existing AppVeyor config files.

    $ cat .appveyor.yml version: 1.0.{build} branches: except: - /travis/ skip_tags: true cache: - C:\strawberry -> .appveyor.yml install: - if not exist "C:\strawberry" cinst strawberryperl - set PATH=C:\strawberry\perl\bin;C:\strawberry\perl\site\bin;C:\str +awberry\c\bin;%PATH% - cd C:\projects\%APPVEYOR_PROJECT_NAME% - cpanm --installdeps . build_script: - perl Makefile.PL - gmake test_script: - gmake test TEST_VERBOSE=1 notifications: - provider: Email to: - jkeenan@cpan.org on_build_status_changed: true

    However, the AppVeyor process repeatedly fails. Here's the relevant part of the output:

    If I download the log.txt file from this run, the last 10 to 12 lines match the tail of the output above.

    My other distros using .appveyor.yml configuration files build and test as expected, so I am at a lost as to explain why this one does not. Any suggestions?

Curious behavior of Use
4 direct replies — Read more / Contribute
by geoffleach
on Feb 20, 2025 at 13:04
    I have a number of scripts that load a particular module, using use in the usual way. In creating a new script that access the module in the same way,
    use lib path use module
    fails with a syntax error in the module. On the other hand,
    require path/module.pm
    executes as expected. using
    BEGIN ...
    does not effect either result. I would appreciate suggestions on what might be going on, or guidance on how to discover what Perl might be objecting to in the module, which (to repeat myself) compiles without error.
Headless testing of Tk under Xvfb (Solved)
1 direct reply — Read more / Contribute
by choroba
on Feb 19, 2025 at 09:47
    Hi all. I'm trying to give an old Tk application some love, and I noticed it had many tests that nobody had run for many years: many of them were failing.

    I fixed all of them, and to prevent the same situation in the future, I decided to run the tests in GitHub Actions. One of the tests needs the Tk application to run, so I decided to run it headless in Xvfb.

    The test failed in Xvfb, not only in GH Actions, but even when I ran it locally. In a real X session, it passed.

    I was able to reduce the test to the following:

    #!/usr/bin/perl use strict; use warnings; use Tk; my $mw = 'Tk::MainWindow'->new; my $current = 0; my @buttons = map { my $i = $_; $mw->Button(-text => $i, -command => sub { $current = $i } )->pack } 1, 2; $mw->after(100, sub { $mw->eventGenerate('<KeyPress>', -keysym => $_) for qw( Tab Return ); $mw->idletasks(); $mw->DESTROY; }); Tk::MainLoop(); use Test::More tests => 1; is $current, 1, 'Events processed';

    Steps to reproduce:

    $ tktest.pl 1..1 ok 1 - Events processed $ Xvfb :19 & $ pid=$! $ DISPLAY=:19 tktest.pl 1..1 not ok 1 - Events processed # Failed test 'Events processed' # at /home/choroba/tktest.pl line 27. # got: '0' # expected: '1' # Looks like you failed 1 test of 1. $ kill $pid

    Update: Under Xvnc, the behaviour is the same as under Xvfb, i.e. the events are ignored, even when I run the test from an xterm in a vnc viewer.

    map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]
Undefined value returned on call to readline (<>)?
3 direct replies — Read more / Contribute
by Intrepid
on Feb 16, 2025 at 22:35

    Dear Monks, it's good to know we can still reach each other. Perlmonks was completely offline a couple days ago. I felt like someone had stabbed me in the shoulder blade.

    So what I am doing this cold winter's eve is playing Mr. Helpful with someone else's code, again. Tonight, it's Proc-PID-File 1.29. In running the test suite I tripped several instances of the warning Use of uninitialized value in pattern match (m//) at blib/lib/Proc/PID/File.pm line 286. I will in the interests of convenience to the reader, show the subroutine (with inserted comment by me) below:

    # Returns the process id currently stored in the file set. If the met +hod # is passed a file handle, it will return the value, leaving the file +handle # locked. This is useful for atomic operations where the caller needs + to # write to the file after the read without allowing other dirty writes +. # # Please note, when passing a file handle, caller is responsible for # closing it. Also, file handles must be passed by reference! sub read { my ($self, $fh) = @_; sysopen($fh, $self->{path}, O_RDWR|O_CREAT) || die qq/Cannot open pid file "$self->{path}": $!\n/; flock($fh, LOCK_EX | LOCK_NB) || die qq/pid "$self->{path}" already locked: $!\n/; # WARNING: Use of uninitialized value in pattern match (m//): my ($pid) = <$fh> =~ /^(\d+)/; close $fh if @_ == 1; $self->debug("read(\"$self->{path}\") = " . ($pid || "")); return $pid; }

    Is readline really returning undefined? If so, under what conditions (aside from an empty file) would readline return undef? If it would do no harm, we could sort it by saying no warnings "undefined"; in the scope of the subroutine. Any observations, good monks?

    Feb 17, 2025 at 03:30 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)

Better Hash Tables?
5 direct replies — Read more / Contribute
by QM
on Feb 15, 2025 at 11:07
    Do we know anything more useful about this?

    Undergraduate Upends a 40-Year-Old Data Science Conjecture

    Paper on arxiv

    Since Perl uses linked lists when collisions occur, most (all?) of this new work seems irrelevant?

    What are the methods used in other langauges / implementations?

    In my brief research, it seems the only marginally questionable thing that Perl does is not resize based on collisions. It seems, in the worst case, all entries go in the same bucket, but a resize isn't triggered until 75% loading factor is reached?

    -QM
    --
    Quantum Mechanics: The dreams stuff is made of

Recursively substitute against multidimensional hash
2 direct replies — Read more / Contribute
by Maelstrom
on Feb 14, 2025 at 01:58
    Apologies if I have my terminology wrong but I have a module that will substitute %foo with $var{'default'}{'foo'} and %foo.bar with $var{'foo'}{'bar'} doing something like
    $work =~ s{%(\w+)(?:\.(\w+))?}{ defined $2 ? $var{$1}{$2} : $var{default}{$1} }eg;
    I'd like to extend this to cover any level of nesting so that %a.deeply.nested.value would return $var{'a'}{'deeply'}{'nested'}{'value'} and the only thing I've come up with is a function that splits on the '.' and loops through the array to build a statement I can eval but I'm sure there has to be a more elegant way. If possible I'd like to avoid lookbehinds/lookaheads to keep the code portable to languages that don't support that. I'm also thinking I should I should be using $var{'foo'} instead of $var{'default'}{'foo'} so feel free to leave that out of any suggested 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, 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.