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
Any caveats in using unpack to right-trim? Why isn't it advertised more?
8 direct replies — Read more / Contribute
by Anonymous Monk
on Feb 08, 2025 at 06:52

    Suppose I'm not targeting latest Perl versions and their 'trim' built-in, and reluctant to depend on other modules, -- then practically every FAQ or cookbook or tutorial recommend what's "usual" method in test below. Now, I have fair amount of medium-size "records" (variable length and containing white-space somewhere in the middle, NOT as in test below), which may terminate in unpredictable WS sequences, which I want to trim. Performance freak, I've been unsatisfied with the speed and came with "better" version. Then accidentally discovered "unpack" method. Now I'm puzzled if this nice and fast way is kept secret and why :-)

    use strict; use warnings; use 5.014; # s///r use Benchmark 'cmpthese'; my @a = map { ( 'a' x 123 ) . ( ' ' x rand 2 ) . ( "\n" x rand 2 ) } 0 .. 999; cmpthese -1, { usual => sub { my @ret = map { s/\s*$//r } @a; \@ret }, better => sub { my @ret = map { s/.*\S\K\s*$//sr } @a; \@ret }, unpack => sub { my @ret = map { unpack 'A*', $_ } @a; \@ret }, }; __END__ Rate usual better unpack usual 159/s -- -88% -95% better 1284/s 707% -- -56% unpack 2899/s 1722% 126% --
Anyone familiar with DBD:Mock?
2 direct replies — Read more / Contribute
by cLive ;-)
on Feb 07, 2025 at 13:08

    Trying to work out why this isn't returning all the rows of data from the mock. Have I messed up the session instantiation?

    use v5.36; use DBI; use DBD::Mock; use Data::Dumper; my $session = DBD::Mock::Session->new('testing' => ( { statement => 'SELECT * FROM bar', results => [ ['one', 'two'], ['three', 'four'] ], } )); my $dbh = DBI->connect('dbi:Mock:', '', '') or die $DBI::errstr; $dbh->{mock_session} = $session; my $data = $dbh->selectall_arrayref("SELECT * FROM bar"); say Dumper({ DATA => $data });

    Output:

    $VAR1 = { 'DATA' => [ [ 'three', 'four' ] ] };
new rakudo star release, how to upgrade
1 direct reply — Read more / Contribute
by vincentaxhe
on Feb 05, 2025 at 21:44
    I have rakudostar 2024-06-01 version installed, now New version 2025-01-01 have released, How to upgrade, the install script 'rstar' did not have a upgrade option, do I have to wipe all and reinstall all, or it's better to use aur to get moarvm core isolated and easy to upgrade.
next unless not working
4 direct replies — Read more / Contribute
by anitaord
on Feb 05, 2025 at 11:57
    Hello, I am new to Perl and I have a question, perhaps is a little but silly but I have a txt doc with several lines where each line is a programming language and I want to print allthe lines except for Java, and I have this piece of code but it doesn't do anything, it stays at: "Reading file", I would appreciate any help or if you know of a link where I can further study the next-unless, Thanks.
    open(FH, "/Users/anaordonez/Documents/my_languages.txt")or die "Sorry! +! couldn't open"; print "Reading file \n"; # Reading the file till FH reaches EOF while(<>) { # Printing one line at a time next unless $_ = "Java"; print $_; } close;
Puzzled by the bignum pragma
1 direct reply — Read more / Contribute
by syphilis
on Jan 31, 2025 at 04:57
    Why does bignum assign integer values to Math::BigInt objects ?
    Why not assign them to a Math::BigFloat object, same as is done for non-integer values ?
    By allowing 2 types of objects, bignum opens itself up to issues that (AFAICS) would not arise if all values were assigned to Math::BigFloat objects - eg upgrades/downgrades from one type to another.
    And I can't see that allowing Math::BigInt objects leads to any benefits.

    Illuminations are most welcome.

    Cheers,
    Rob
Apache::ASP issue
1 direct reply — Read more / Contribute
by tchatz
on Jan 30, 2025 at 16:54
    I have the following lines in my global.asa
    if ($path[0] eq 'cms' && ($path[1] eq 'auth' || $path[1] eq 'upload')) + { $Response->{Status} = 403; $Response->End(); return; }
    The problem is that status is undef if i warn Dumper($Response), and also in the headers of the response on the client side the status is 200

    Only if I use $Server->Transfer( "index.asp" ) instead of $Response->End(); only then I get the 403 status but then I get the following error in the logs.

    error executing code for include /opt/apache/htdocs/..../index.asp: no + include
    Which makes sense because the index.asp does not exist.

    But why when there is an error then the status does change to 403, and when I just use $Reponse->End() or just return, it doesn't work?

    I would appreciate if someone shares some light into this Thanks for you time and consideration
Why does "flush filehandle" work?
3 direct replies — Read more / Contribute
by chengiz5
on Jan 29, 2025 at 07:59

    While writing a perl script, I wanted to flush a handle, and wrote

    flush $gp;

    like the C coder I am. The code worked. Then while cleaning up the syntax for consistency, I added parens, i.e. flush($gp), but this did not work. Turns out flush is not a function (it's not in perlfunc). So why did my first attempt work?

How to remove triple characters?
No replies — Read more | Post response
by harangzsolt33
on Jan 28, 2025 at 23:33
    Update: I think, I got this figured out before anybody saw it. lol


    I have a little exercise which might sound like homework, but I promise you it isn't! Lol And I almost got it to work, but I can't figure out how to make the last function do what it's supposed to. Update: *Got it!

    So, I wanted to write four functions--one that doubles certain characters in a string and another sub that removes double characters from a string. I think I want to clarify that what I want is not this:

    $S =~ tr| ||s;

    I know, this would collapse multiple spaces to a single space, but that's not what I want to do. I want to do this: "AAAAAA" => "AAA" just replace each pair with a single character. OK. So, I already figured out how to do this.

    But then I want to write another sub that repeats certain characters N number of times and finally a last one that finds N number of occurrences of certain characters in a string and replaces each group of characters with one character.
    Find groups of 3 letter A's and replace them: "AAAAAA" => "AA"

    I'm having trouble with this last sub. It just doesn't want to do what I want. Can someone please help me show me how to do this? It's called SingleCharsX()

    #!/usr/bin/perl use strict; use warnings; # This should print: "AABBC" print "\n", DoubleChars("ABC", "AB"); # This should print: "LALA LLAALLAAN N" print "\n", SingleChars("LALA LLLAAALLLLAAAAN NN", "LANG"), "\n\n"; # Okay. Now, make it more complicated... foreach (2..7) { print "\n x $_ : |", DoubleCharsX("ABCD", "ABXY", $_), "|"; } print "\n\n"; foreach (2..7) { print "\n x $_ : |", SingleCharsX("LLLLLLLL-AAAAAAAA", "ABX", $_), "|"; } exit; ############################################ ## FUNCTIONS ## ############################################ # This function doubles every instance of a list of characters in # a string and returns a new string. For example, it can be used # to double every instance of space or new line characters. # # DoubleChars("Helo World!", "!lo ") => "Helloo Woorlld!!" # DoubleChars("Helo World!", "HHH") => "HHelo World!" # # Usage: STRING = DoubleChars(STRING, CHARS) # sub DoubleChars { defined $_[0] && length($_[0]) or return ''; defined $_[1] && length($_[1]) or return $_[0]; my $S = $_[0]; $S =~ s/([\Q$_[1]\E]{1})/$1$1/g; return $S; } ############################################ # # This function removes certain characters that appear twice next # to each and leaves only one instance. This can be used to undo # the effects of the DoubleChars() function. # # SingleChars(" HEELLLLLLO OO!", "OL") => " HEELLLO O!" # SingleChars("AABBCAABBC", "AB") => "ABC" # # Usage: STRING = DoubleChars(STRING, CHARS) # sub SingleChars { defined $_[0] && length($_[0]) or return ''; defined $_[1] && length($_[1]) or return $_[0]; my $S = $_[0]; $S =~ s/([\Q$_[1]\E]{1})\1/$1/g; return $S; } ############################################ # This function doubles or triples every instance of # a list of characters in a string and returns a new string. # For example, it can be used to repeat every instance of # the exclamation point. The second argument tells what # to repeat, and the third argument tells how many times # to repeat those characters. # # DoubleCharsX("Hello World!", "!", 3) => "Hello World!!!" # # Usage: STRING = DoubleCharsX(STRING, CHARS, [REP]) # sub DoubleCharsX { defined $_[0] && length($_[0]) or return ''; defined $_[1] && length($_[1]) or return $_[0]; my $REP = defined $_[2] ? int($_[2]) : 2; $REP >= 2 or $REP = 2; my $S = $_[0]; $S =~ s/([\Q$_[1]\E]{1})/$1 x $REP/ge; return $S; } # This function doubles or triples every instance of # a list of characters in a string and returns a new string. # For example, it can be used to repeat every instance of # the exclamation point. The second argument tells what # to repeat, and the third argument tells how many times # to repeat those characters. # # SingleCharsX("Pressss a keeeeyyy!", "ey", 3) => "Pressss a keey!" # # Usage: STRING = SingleCharsX(STRING, CHARS, [REP]) # sub SingleCharsX { defined $_[0] && length($_[0]) or return ''; defined $_[1] && length($_[1]) or return $_[0]; my $REP = defined $_[2] ? int($_[2]) : 2; $REP >= 2 or $REP = 2; my $S = $_[0]; foreach my $CHAR (split(//, $_[1])) { $S =~ s/\Q$CHAR\E{$REP}/\Q$CHAR\E/g; } return $S; }

    Update: Also, I am not sure how one should call these subs. I mean DoubleCharsX is not a very creative name. Maybe RepChars() would be better? But then how would I call SingleCharsX() ? The other thing is I don't even know what kind of title to give this thread. I'm not very good at naming these things. :P

    Update: I think, everything works fine, it's not that the program doesn't do what it's supposed to, but I was expecting a different output. And since the output didn't match what I imagined it should be, I thought it was an error. I thought it should print something like this:

    AABBC LALA LLAALLAAN N x 2 : |AABBCD| x 3 : |AAABBBCD| x 4 : |AAAABBBBCD| x 5 : |AAAAABBBBBCD| x 6 : |AAAAAABBBBBBCD| x 7 : |AAAAAAABBBBBBBCD| x 2 : |LLLLLLLL-AAAAAA| x 3 : |LLLLLLLL-AAAAA| x 4 : |LLLLLLLL-AAAA| x 5 : |LLLLLLLL-AAA| x 6 : |LLLLLLLL-AA| x 7 : |LLLLLLLL-A| AND INSTEAD IT WAS PRINTING THIS: AABBC LALA LLAALLAAN N x 2 : |AABBCD| x 3 : |AAABBBCD| x 4 : |AAAABBBBCD| x 5 : |AAAAABBBBBCD| x 6 : |AAAAAABBBBBBCD| x 7 : |AAAAAAABBBBBBBCD| x 2 : |LLLLLLLL-AAAA| x 3 : |LLLLLLLL-AAAA| x 4 : |LLLLLLLL-AA| x 5 : |LLLLLLLL-AAAA| x 6 : |LLLLLLLL-AAA| x 7 : |LLLLLLLL-AA|
Trying to pass Hash to Module
3 direct replies — Read more / Contribute
by mcoblentz
on Jan 28, 2025 at 20:31
    Hello all, I am probably over my head here, but here goes. I'm trying to pass a hash to a module and it's not working. In my main script, I define a 'module_map' which lists all the modules and calls to them.
    sub process_modules { my ($active_modules_ref) = @_; # Accept %active_modules as a refe +rence my %module_map = ( 'clouds' => sub { CloudUpdate::cloud_update() }, 'volcanoes' => sub { VolcanoXML::process_volcano_data() }, 'storms' => sub { Storm::fetch_and_process_storms() }, 'quakes' => sub { Earthquake::get_quakedata() }, 'norad' => sub { my $satellite_file = "$xplanet_satellites_dir\\Norad"; my $output_tle_file = "$xplanet_satellites_dir\\Norad.tle" +; my $marker_file = "$xplanet_satellites_dir\\Norad_marker.t +xt"; Norad::process_satellites($satellite_file, $output_tle_fil +e, $marker_file); }, 'fires' => sub { Fires::run() }, 'labelupdate' => sub { print "process_modules - Debug: Calling WriteoutLabel with + active_modules_ref:\n" if $DEBUG; foreach my $key (keys %$active_modules_ref) { print " $key => $active_modules_ref->{$key}\n" if $DE +BUG; } Label::WriteoutLabel($active_modules_ref); # Pass as a re +ference }, ); foreach my $module (keys %Globals::modules) { my ($onoff_key) = grep { /onoff$/i } keys %{ $Globals::modules +{$module} }; if ($onoff_key && $Globals::modules{$module}{$onoff_key} == 1) + { print "Processing module: $module\n" if $DEBUG; if (exists $module_map{$module}) { $module_map{$module}->($active_modules_ref); } else { warn "No subroutine mapped for module: $module\n" if $ +DEBUG; } } else { print "Module: $module, On/Off: Undefined or Inactive\n" i +f $DEBUG; } } }
    The key module in this 'process_modules' subroutine is the labelupdate call
    'labelupdate' => sub { print "process_modules - Debug: Calling WriteoutLabel with + active_modules_ref:\n" if $DEBUG; foreach my $key (keys %$active_modules_ref) { print " $key => $active_modules_ref->{$key}\n" if $DE +BUG; } Label::WriteoutLabel($active_modules_ref); # Pass as a re +ference
    Given that's the call to use, then my main script invokes process_modules as follow:
    # Process modules process_modules(\%active_modules);
    Where the program goes off to the Label::WriteoutLabel routine and dies because the hash is undefined. I can't figure out how to pass the hash in. I double checked the process_modules call uses '\%...' so I am stumped. Oh, the WriteoutLabel routine reads as follows:
    package Label; use strict; use warnings; use Data::Dumper; use Time::Local; # Load the Time::Local module use Globals qw( $DEBUG $label_file $labelsettings ); sub WriteoutLabel { print "Label line 31 - Debug: \$DEBUG is " . ($DEBUG ? "enabled" : + "disabled") . "\n"; my ($active_modules_ref) = @_; # Skip label generation if labelsdisplay is disabled my $labels_display = $Globals::modules{'labels'}{'labelsonoff'} // + 1; # Default to 1 (enabled) return unless $labels_display; print "Label line 39 - Debug: Labels display is " . ($labels_displ +ay ? "enabled" : "disabled") . "\n" if $DEBUG; # Debug: Check that active_modules_ref is a hash reference unless (ref $active_modules_ref eq 'HASH') { print "Label::WriteoutLabel - Received invalid active_modules_ +ref: " . (ref $active_modules_ref || 'undefined') . "\n" if $DEBUG; die "Error: active_modules_ref is not a HASH reference."; } ...
    I have tried my ($self, $active_modules_ref) = @_; and varieties thereon. Thank you in advance,
DBI supporting ed25519 ?
1 direct reply — Read more / Contribute
by Andy16
on Jan 28, 2025 at 09:10
    Hi out there


    I need to connect to a MariaDB using ed25519

    I fail in "Authentication plugin 'client_ed25519' cannot be loaded: Incompatible client plugin interface" using DBI and connecting to "DBI:MariaDB:database=..."

    Anyone succeeded in that? Is it possible? What do I miss?

    installed are:
    DBI
    DBD::mysql
    DBD::MariaDB
    (among others)

    thanks so much!

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.