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
Getting list of network interfaces
2 direct replies — Read more / Contribute
by Anonymous Monk
on Mar 25, 2026 at 20:17
    I need to get the list of network interface names and the network addresses to which they are bound. Unfortunately there's no standard method for this, and the two recommended CPAN modules (IO::Interface and Net::Interface) are buggy and unmaintained. So I am currently parsing the output of `ifconfig -a` or `ip addr show`. This works for my test machines, but I'm planning on distributing the script, so need to maximize portability among unixes.

    Using SIOCGIFCONF looks like an interesting alternative, but the only perl example I found is very non-portable: Re: How do I get the local internet IP address?. sys/ioctl.ph isn't present in any of my perlbrewed perls, and even after running h2ph, it fails with "unsupported architecture" for macOS. But I did confirm with the following C program that SIOCGIFCONF is relatively portable when implemented right: https://gist.github.com/OrangeTide/909204.

    Is there an alternative I missed?

Win32::OLE & encoding
2 direct replies — Read more / Contribute
by Denis Mikhailov
on Mar 25, 2026 at 09:44

    Hello.

    I am reading a .docx file in Russian. The code $text =~ s/^Испытательная(.*?)/\1/ug; is supposed to process a line by removing part of the text. If the text is written in English, everything is detected and trimmed correctly, but I cannot get it to work with Russian text. In the console, instead of Russian text, I see garbled characters. I've been dancing around encodings — utf8, utf16, cp1251, cp1252 — but none of them give the desired result. Apparently, I am doing something wrong.

    Important! When the text is written to a text file from the Word document, it displays correctly.

    I would appreciate your help. Thank you.

    #!/usr/bin/perl use Win32::OLE; use Win32::OLE::Enum; use utf8; use strict; my $text; my $paragraph; my $document = Win32::OLE -> GetObject($ARGV[1]); open (FH,">$ARGV[0]") || die "Can't open file: $!\n"; my $paragraphs = $document->Paragraphs(); my $enumerate = new Win32::OLE::Enum($paragraphs); while(defined($paragraph = $enumerate->Next())) { $text = $paragraph->{Range}->{Text}; $text =~ s/^Испытат&#107 +7;льная(.*?)/\1/ug; $text =~ s/[\n\r]//g; print FH "$text\n"; }
[OT] Is It Possible To Serialize A Chess Board In Fewer Than 23 Bytes?
5 direct replies — Read more / Contribute
by Limbic~Region
on Mar 10, 2026 at 12:31
    All,
    Disclaimer: This is not a Perl question though I have often found working on memory management problems like this helps improve my Perl. Additionally, I am not a chess player - I have probably played less than a dozen games in my life so I may be way off base here.
    • First 8 bytes = 64 bit string representing the positions of the white pieces on the board
    • Next 8 bytes = 64 bit string representing the positions of the black pieces on the board
    • Next 6 bytes = Sixteen 3 bit strings representing the white pieces (pawn, rook, knight, bishop, king, queen)
    • Next 1 byte = 1 bit representing black/white's turn, 4 bits representing what type of castling is still possible, 3 bits representing the column the last turn moved the pawn 2 places

    That last 3 bits may be hard to understand but in en passant, if your opponent moves 2 places to avoid being attacked by a pawn you already have in position, you have the option to capture that pawn but you must immediately do so on your next turn. These bits serve to either tell you that en passant is possible and which piece is able to be attacked, or if en passant is not possible is set to an invalid column.

    There are admittedly a few things that these 23 bytes do not encode:
    • Previous board configurations leading to the three-fold repetition or five-fold repetition draw rules
    • Number of previous moves without pawn move or capture for 50/75 move draw rules
    • Time remaining for each player if time control is employed

    While the 3 or 5 board position repetition is beyond the scope of this approach (you would essentially have to serialize every board from every move), you could fairly easily add a byte or two in order to address time and 50/75 move draw rules if you wanted.

    An interesting aspect of the approach I have provided is that you can go with either fixed length records (every serialized board is 23 bytes) or with variable length since the number of white and black pieces can be read from the first 16 bytes.

    My question to you is - can you see a way to save any more space? This was a thought experiment so I have no practical use but it did keep me up for a long time so I want to make sure I am not missing something sneaky/creative.

    Cheers - L~R

Count assertions
3 direct replies — Read more / Contribute
by 1nickt
on Mar 10, 2026 at 05:20

    Hi all, with the following test file how do I get prove to report 6 (assertions) rather than 2 (subtests)?

    use Test::More; subtest foo => sub { ok 1; ok 2; ok 3; }; subtest bar => sub { ok 4; ok 5; ok 6; }; done_testing;

    Thanks!


    The way forward always starts with a minimal test.
An anomaly with Filesys::DfPortable, I need your eyes
2 direct replies — Read more / Contribute
by Intrepid
on Mar 09, 2026 at 14:47

    I'm getting an unexpected result from an attempt to use a module, Filesys::DfPortable, on CPAN. I'm seeing the same results in blocks, with different filesystems used as arguments to dfportable. The output of my code looks like this:

    $ perl ~/Documents/perl-libdirs-installTime.pl
    /usr/lib/perl5/5.40/x86_64-cygwin-threads  installarchlib
    Total 1k blocks used in installarchlib:  175,087,368
    /usr/share/perl5/5.40                      installprivlib
    Total 1k blocks used in installprivlib:  175,087,368
    

    So here's the code I'd like help with:

    #!/usr/bin/env perl # use strict; use warnings; use Config; use Number::Format qw(:subs); use Filesys::DfPortable; my $mlen = 0; my %hop; my @lodirs = qw(installarchlib installprivlib); for (@lodirs) { my $p = $Config{ $_ }; $mlen = length( $p ) > $mlen ? length( $p ) : $mlen; $hop{ $_ } = $p; } $mlen += 2; for (sort keys( %hop )) { printf( "%-${mlen}s%s\n", $hop{ $_ }, $_ ); my $mea = dfportable( $hop{ $_ }, 1024 ); printf "Total 1k blocks used in %s: %s\n", $_ , format_number( $mea->{bused} ); }

    I started working on this little script in Linux and I see the same anomalous results on CygPerl. I don't think it's a PEBKAC but I need other eyes to check it out. Thanks very much, Monks / Nuns.

        – Soren
    Apr 01, 2026 at 23:26 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)

A little overloading conundrum
2 direct replies — Read more / Contribute
by syphilis
on Mar 06, 2026 at 19:46
    Hi,

    I have a module A that overloads the '-' operator via its A::oload_minus() subroutine.
    And I have a second module B that also overloads the '-' operator via it's own B::oload_minus() subroutine.
    Both modules also have their own oload_add, oload_mul, oload_div, oload_mod and oload_pow subroutines that overload the other basic arithmetic operators).

    I have constructed the overloading in module A to handle B objects.
    But if module B's overloading subroutines are passed a module A object, it is (by my current design) a fatal error.
    use A; use B; $A_obj = A->new(16); $B_obj = B->new(6); my $n1 = $A_obj - $B_obj; # $n1 is an A object with value 10 my $n2 = $B_obj - $A_obj; # Fatal error
    In the above demo I want $n2 to be an A object, with the value of -10.
    That is, I want the A::oload_minus() sub to receive the args ($A_obj, $B_obj, TRUE).
    Instead, the B::oload_minus() sub is receiving the args ($B_obj, $A_obj, FALSE) - which is, by my current design, a fatal error since B::overload_minus() does not currently accept A objects.

    Is there a way that I can work around this without making any changes to the B module ? (The motivation to not alter module B is simply that I don't want to add more clutter to B unless I need to.)

    My module "A" is in fact Math::MPC, and my module "B" is in fact Math::MPFR.

    AFTERTHOUGHT: I should point out that the arithmetic overloading in the publicly available versions of Math::MPC don't yet accept Math::MPFR objects. (I've currently implemented this new feature on my local Math::MPC builds only.)

    Cheers,
    Rob
Type coercion and union
2 direct replies — Read more / Contribute
by tomred
on Mar 06, 2026 at 12:29

    I have the following Type defined.

    package Types; use v5.34; use warnings; use Type::Utils qw( as coerce declare from via ); use Types::Common qw( Enum Str ); use Type::Library -base, -declare => qw( CreditType InvoiceType ); declare InvoiceType, as Enum [qw/ ACCPAY ACCREC /]; coerce InvoiceType, from Str, via { #warn "Trying to coerce $_\n"; my %types = ( Invoice => 'ACCREC', SupplierInvoice => 'ACCPAY', ); #my $ret = $types{$_}; #warn "Returning $ret\n"; return $types{$_}; } ; declare CreditType, as Enum [qw/ ACCPAYCREDIT ACCRECCREDIT /]; coerce CreditType, from Str, via { warn "Trying to coerce $_\n"; my %types = ( Credit => 'ACCRECCREDIT', SupplierCredit => 'ACCPAYCREDIT', ); my $ret = $types{$_}; warn "Returning $ret\n"; return $types{$_}; } ; 1;

    I have a class that uses the types as a union, this or that

    package MyApp; use v5.34; use warnings; use Moo; use Types qw/ InvoiceType CreditType /; has 'type' => ( is => 'ro', isa => InvoiceType | CreditType, required => 1, coerce => 1, ); sub run { my ($self) = @_; say "Running with ".$self->type; } 1;

    I have a test to make sure it's doing what I expect `t/type.t`

    #!/opt/perl5/bin/perl use v5.34; use warnings; use Test::More; use Types qw( InvoiceType CreditType ); { subtest 'Type coercion' => sub { is InvoiceType->coerce('Invoice'), 'ACCREC', 'Can coerce a sales invoice'; is InvoiceType->coerce('SupplierInvoice'), 'ACCPAY', 'Can coerce a supplier invoice'; is CreditType->coerce('Credit'), 'ACCRECCREDIT', 'Can coerce a credit type'; is CreditType->coerce('SupplierCredit'), 'ACCPAYCREDIT', 'Can coerce a supplier credit type'; }; } { my $class = 'MyApp'; use_ok($class); subtest 'Class coercion' => sub { for my $t ( qw/Invoice SupplierInvoice Credit SupplierCredit / + ) { note "Type=$t"; my $x = new_ok($class => [ type => $t ]); note "Now Type=".$x->type; } }; } done_testing;
    t/type.t .. # Subtest: Type coercion ok 1 - Can coerce a sales invoice ok 2 - Can coerce a supplier invoice ok 3 - Can coerce a credit type ok 4 - Can coerce a supplier credit type 1..4 ok 1 - Type coercion ok 2 - use MyApp; # Subtest: Class coercion # Type=Invoice ok 1 - An object of class 'MyApp' isa 'MyApp' # Type=SupplierInvoice ok 2 - An object of class 'MyApp' isa 'MyApp' # Type=Credit not ok 3 - MyApp->new() died # Failed test 'MyApp->new() died' # at t/type.t line 31. # Error was: Undef did not pass type constraint "InvoiceType| +CreditType" (in $args->{"type"}) at /home/dpaikkos/spl/local/lib/perl +5/Test/More.pm line 741 # "InvoiceType|CreditType" requires that the value pass "Credi +tType" or "InvoiceType" # Undef did not pass type constraint "InvoiceType" # "InvoiceType" is a subtype of "Enum["ACCPAY","ACCREC"]" # "Enum["ACCPAY","ACCREC"]" requires that the value is def +ined # Undef did not pass type constraint "CreditType"

    I excel at leaving typos in my code but I am pretty sure there are none in the code so far. The coercions appear to work in a stand alone fashion but when used as a union, the 2nd Type does not appear to apply the coercion. If I swap the "CreditType" to be the first item, I find that the InvoiceType fails.

    I suspect I could use some kind of named parameterized coercion and `plus_coercions` but I hit this snag and haven't been able to move forward.

    Does anyone have any insights into what I'm doing wrong?

    Thanks in advance
WebPerl in a Progressive Web App?
1 direct reply — Read more / Contribute
by LanX
on Mar 06, 2026 at 08:52
    Hi

    Is it possible to run WebPerl inside a PWA?

    Hence effectively running Perl inside an app which can be installed on Android, Win, Linux?

    Has it been attempted yet?

    What are the results?

    Does it reduce the startup time of Perl because it's running hot in the background?

    Cheers Rolf
    (addicted to the Perl Programming Language :)
    see Wikisyntax for the Monastery

Tieing STDERR to a textbox causes the IPC::Run start function to fail
2 direct replies — Read more / Contribute
by CrashBlossom
on Mar 05, 2026 at 20:28
    Greetings Monks, I am running strawberry perl 5.30 under windows 11.

    When the program below reaches the start function, it fails with the seemingly nonsensical error "Can't locate auto/Tk/ROText/FILENO.al". Tieing only STDOUT to the same widget is no problem.

    Does anyone have any insight as to what is happening here?

    use warnings; use strict; use IPC::Run qw(start pump finish timeout); use Tk; require Tk::ROText; my $mw = MainWindow->new(-title => " NON BLOCKING"); my $outw = $mw->Scrolled('ROText', -font => "{Courier New} 10 bold", -background => 'DarkBlue', -foreground => 'OldLace', -scrollbars => 'se', -wrap => 'none', -width => 100, -height => 10, )->pack(-fill => "both", -expand => 1); + # tie *STDOUT, 'Tk::Text', $outw; tie *STDERR, 'Tk::Text', $outw; my ($in, $out, $err) = ('', '', ''); my $h; if (! defined(eval { $h = start ['cmd.exe', '/c', 'dir'], \$in, \$out, + \$err; })) { print "\nStart failed: $@\n"; } while($h->pumpable) { $h->pump; print $out; $out = ''; } $h->finish; MainLoop;
pp's tmp folder content execution
1 direct reply — Read more / Contribute
by DomX
on Feb 19, 2026 at 11:51

    Dear Monks, here monk Dominik, asking my siblings for wisdom.

    I'm a fan of using pp to make standalone programs since v5.40.0, because it lets me use the new Perls and doesn't mess the target system by installing anything by sudo cpan somewhere nobody is finding things again or making updates at all.

    Long story short: Delivering a pp archive is already pretty neat, but I'd like to go a step further. The application extracts itself to /tmp/par-<user name hash>/cache-<app hash or -T string> (or similar) by default. So, what I thought, to reduce the startup time, which is really poor for pp executables, compared to native Perl, I'd like to omit the extraction and verification step of the pp binary, but directly start the interpreter from the /tmp/par-.../cache-... directory, with the script as argument. Something I think the pp binary is doing. But the executables and libraries have very obscure names, so I don't know, what exact I need to execute to start up the interpreter from /tmp/par-.../cache-...

    Maybe I'm completely wrong on this path anyway and this is any magic within the pp binary itself, not just from this folder.

    So, what I actually try to achieve is: having a unpacked Perl interpreter, running my scripts, for example:

    $ cat /usr/bin/myapp #!/usr/bin/env bash /usr/libexec/myapp/perl /usr/libexec/myapp/myapp.pl "$@"

    I know, I could just compile a Perl residing entirely withing /usr/libexec/myapp, but maybe there is a more simple way to do so?


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.