The Science Perl Journal, Issue #1 (Vol. 1, No. 1) is finally here!

blogs.perl.org

Published by Brett Estrade on Friday 18 October 2024 04:32

After hundreds of hours of work and support from lots of people, the long promised Journal is here. That link will take you to some more information, on there a link to purchase is available. All proceeds go to supporting future Issues and events of the SPC and Perl Community Organization. At this time, an electronic version is not available due to end-of-year time constraints.

It may seem silly, but we spent extra time making sure the book spine looks good on a bookshelf and will look even better as the Issues accrue. Get it while it's hot. ISBN-13: 9798218984748, 152 pages.

Some of us are currently preparing for a block of Science Perl Talks at the London Perl & Raku Workshop 2024. We appreciate the organizers of this event for the opportunity.

More will be posted after the LPW, but the SPC is hosting the Perl Community Conference, Winter 2024 on December 18th (Perl's 37th birthday! :-)). If you are interested in getting published in the next Issue of the SPJ (Winter 2024), we are still accepting extended abstracts, which is up to 1 full page in the Journal and a 5 minute lightning talk slot at the Winter Conference.

This week in PSC (164) | 2024-10-17

blogs.perl.org

Published by Perl Steering Council on Friday 18 October 2024 00:39

This week, we talked about some recent (and less recent) p5p threads:

  • We discussed the sort thread briefly. We are waiting to see where it goes.
  • We talked again about TLS in core, and reviewed a document from the CPAN Security Group. We want to talk about this more in depth next week.
  • Discussion of the evalordie thread led us to talk about some form of in-core autodie pragma. We didn’t reach any conclusion.
  • We noted that a maint release is overdue.

Perl Weekly Challenge 291: Poker Hand Rankings

blogs.perl.org

Published by laurent_r on Thursday 17 October 2024 12:46

These are some answers to the Week 291, Task 2, of the Perl Weekly Challenge organized by Mohammad S. Anwar.

Spoiler Alert: This weekly challenge deadline is due in a few days from now (on October 20, 2024, at 23:59). This blog post provides some solutions to this challenge. Please don’t read on if you intend to complete the challenge on your own.

Task 2: Poker Hand Rankings

A draw poker hand consists of 5 cards, drawn from a pack of 52: no jokers, no wild cards. An ace can rank either high or low.

Write a script to determine the following three things:

1. How many different 5-card hands can be dealt?

2. How many different hands of each of the 10 ranks can be dealt? See here for descriptions of the 10 ranks of Poker hands: https://en.wikipedia.org/wiki/List_of_poker_hands#Hand-ranking_categories

3. Check then the numbers you get in step 2 by adding them together and showing that they're equal to the number you get in step 1.

We need a subroutine (com) for computing the binomial coefficient formula for: n choose k. The simplest formula is: n! / k! (n - k)! But this leads to compute very large numbers that we then divide by other very large numbers. For example, 52! has 68 digits: 52! = 80658175170943878571660636856403766975289505440883277824000000000000. So I prefer to use a formula that considerably simplifies the fraction: n * (n - 1) * ... * (n - k + 1) / k!.
This ought to be faster, but that's not the point, since it is quite fast anyway; the point is that we avoid the risk of integer overflow during intermediate computations. There is no such risk in Raku, and probably also not in Perl, but there are many languages or programming environments that can't handle integers with 68 digits.

Poker Hand Rankings in Raku

See the previous section above for explanations on the com auxiliary subroutine, which really does the bulk of the work.

The poker-hands does only one thing: it populates a hash with the various hand types and their frequencies. This Wikipedia page provides a table with the mathematical expression of the absolute frequency of each hand type. The code did not really need a separate subroutine and could have been inserted in the main code, but I find it clearer this way, in a separate subroutine.

The rest of the program basically displays the hash in a form hopefully readable to the human eye.

sub com ($n, $k) {
    # Binomial coefficient formula for: n choose k
    my $nr_of_com = ([*] ($n - $k + 1)..$n)/([*] 1..$k); 
    return $nr_of_com;
}

sub poker-hands (){
    my %hands =
        "0. RF" => com(4, 1),  # Royal flush 
        "1. SF" => com(10, 1) * com(4, 1) - com(4, 1),
                               # Straight flush
        "2. FK" => com(13, 1) * com(12, 1) * com(4, 1),
                               # Four of a kind
        "3. FH" => com(13, 1) * com(4, 3) * com(12, 1)
            * com(4, 2),       # Full house
        "4. Fl" => com(13, 5) * com(4, 1) - com(10, 1)
            * com(4, 1),       # Flush (excl. RF and SF)
        "5. St" => com(10, 1) * com(4, 1)**5 - com(10, 1)
            * com(4, 1),       # Straight (excl. RF and SF)
        "6. TK" => com(13, 1) * com(4, 3) * com(12, 2)
            * com(4, 1) ** 2,  # Three of a kind
        "7. TP" => com(13, 2) * com(4, 2)**2 *com(11, 1) 
            * com(4, 1),       # Two pairs
        "8. OP" => com(13, 1) * com(4, 2) * com(12, 3)
            * com(4, 1)**3,    # One pair
        "9. NP" => (com(13, 5) - com(10,1)) * (com(4, 1)**5
            - com(4, 1)),      # No pair (or High card)
    ;
    return %hands;
}

my %hand-count = poker-hands;
my $num-hands = com 52, 5;
say "Total number of hands (direct count) => $num-hands";

for %hand-count.keys.sort -> $key {
    say "  - $key => ", %hand-count{$key};
}
say "Sum of the hands by type => ", [+] %hand-count.values;

This program displays the following output:

    $ raku ./poker-hands.raku
    Total number of hands (direct count) => 2598960
      - 0. RF => 4
      - 1. SF => 36
      - 2. FK => 624
      - 3. FH => 3744
      - 4. Fl => 5108
      - 5. St => 10200
      - 6. TK => 54912
      - 7. TP => 123552
      - 8. OP => 1098240
      - 9. NP => 1302540
    Sum of the hands by type => 2598960

Poker Hand Rankings in Perl

This program is essentially a port to Perl of the above Raku program. Please refer to the previous sections if you need explanations.

There is one important change, though: rather than using hand abbreviations (RF, SF, FK, etc.) for the hash keys, it uses hand full name (Royal flush, Straight flush, Four of a kind, etc.), leading to more explicit output.

use strict;
use warnings;
use feature 'say';

sub com  {
    # Binomial coefficient formula for: n choose k
    my ($n, $k) = @_;
    my $fact_k = 1;
    $fact_k *= $_ for 1..$k;
    my $nr_of_com_numerator = 1;
    $nr_of_com_numerator *= $_ for ($n -$k + 1)..$n;
    return $nr_of_com_numerator/ $fact_k;
}

sub poker_hands {
    my %hands =
       ("0. Royal flush" => com(4, 1),
        "1. Straight flush" => com(10, 1) * com(4, 1) 
            - com(4, 1),
        "2. Four of a kind" => com(13, 1) * com(12, 1) 
            * com(4, 1),
        "3. Full house" => com(13, 1) * com(4, 3) 
            * com(12, 1) * com(4, 2), 
        "4. Flush" => com(13, 5) * com(4, 1) - com(10, 1)
            * com(4, 1),       # Flush (excl. RF and SF)
        "5. Straight" => com(10, 1) * com(4, 1)**5 - com(10, 1)
            * com(4, 1),       # Straight (excl. RF and SF)
        "6. Three of a kind" => com(13, 1) * com(4, 3) 
            * com(12, 2) * com(4, 1) ** 2,
        "7. Two pairs" => com(13, 2) * com(4, 2)**2 
            * com(11, 1) * com(4, 1), 
        "8. One pair" => com(13, 1) * com(4, 2) * com(12, 3)
            * com(4, 1)**3,    # 
        "9. No pair" => (com(13, 5) - com(10,1)) 
            * (com(4, 1)**5 - com(4, 1)),      
            # No pair or High card
    );
    return %hands;
}

my %hand_count = poker_hands;
my $num_hands = com 52, 5;
say "Total number of hands (direct count) => $num_hands";

for my $key (sort keys %hand_count) {
    printf "  - %-20s => %-10i \n", $key, $hand_count{$key};
}
my $sum = 0;
$sum += $_ for values %hand_count;
say "Sum of the hands by type => ", $sum

This program displays the following output:

    $ perl ./poker-hands.pl
    Total number of hands (direct count) => 2598960
      - 0. Royal flush       => 4
      - 1. Straight flush    => 36
      - 2. Four of a kind    => 624
      - 3. Full house        => 3744
      - 4. Flush             => 5108
      - 5. Straight          => 10200
      - 6. Three of a kind   => 54912
      - 7. Two pairs         => 123552
      - 8. One pair          => 1098240
      - 9. No pair           => 1302540
    Sum of the hands by type => 2598960

Wrapping up

The next week Perl Weekly Challenge will start soon. If you want to participate in this challenge, please check https://perlweeklychallenge.org/ and make sure you answer the challenge before 23:59 BST (British summer time) on October 27, 2024. And, please, also spread the word about the Perl Weekly Challenge if you can.

Look in to Julia

blogs.perl.org

Published by gg on Thursday 17 October 2024 12:18

To the old Perl programmers out there looking for a new language to learn, I suggest giving Julia a serious look. I haven't had a language bring me this much joy since when I first discovered Perl a long time ago. If Perl is the grandpa, Julia is the granddaughter, and she's a really smart girl. She hangs out with scientists all day helping them make sense of their data, and she does it with a unique style.

To be continued...

(There's so much I want to say, but I don't want to commit the time to write it all down right now.)

Update TiddlyWikis

blogs.perl.org

Published by Ron Savage on Thursday 17 October 2024 09:54

The Perl wiki has been renamed from Perl.html - which was too generic - to Perl.Wiki.html:
https://savage.net.au/misc/Perl.Wiki.html

The Mojolicious wiki is at:
https://savage.net.au/misc/Mojolicious.Wiki.html

The Debian wiki is at:
https://savage.net.au/misc/Debian.Wiki.html

The Personal Security wiki is at:
https://symboliciq.au/misc/Personal.Security.Wiki.html

(Not updated actually...) The Symbolic Language wiki is at:
https://symboliciq.au/misc/Symbolic.Language.Wiki.html

Understanding the Financials of The Perl and Raku Foundation (TPRF)

r/perl

Published by /u/oalders on Thursday 17 October 2024 02:31

I am trying to run an apache web server, which would take my html form, process it, and would give some kind of answer. I had problems installing cgi, configuring it, but I managed to do it. Now I am getting an error "internal server error" when I am trying to check the perl script using curl. When I check the apache error logs, it says that it aborted because of the 3 line, which is: use CGI qw(:standard);

Here is my simple code:

#!/usr/bin/perl
use strict;
use warnings;
use CGI qw(:standard);
use CGI::Carp qw(fatalsToBrowser);

# Enable taint mode
use diagnostics;

print "Content-type: text/html\n\n";
# print header(-type => 'text/html', -charset => 'utf-8'). 
#     start_html('Form Submission Results');

my $sequence = param('sequence');
my $alignment_type = param('alignment-type');
my $organism = param('organism');
my $sequence_length = param('sequence-length');
my $confidence_level = param('confidence-level');

# Check for missing data
if (!$sequence || !$alignment_type || !$organism || !$sequence_length || !$confidence_level) {
    print h1("Error: Missing Data");
    print p("Please fill all the fields.");
    print end_html;
    exit;
}

# Basic validation (simulating complex processing)
if ($sequence !~ /^[ACGT]+$/i) {
    print h1("Error: Invalid Sequence");
    print p("Sequence must contain only A, C, G, or T for DNA.");
    print end_html;
    exit;
}

# Simulate processing
print h1('Sequence Alignment Results');
print p("Alignment Type: $alignment_type");
print p("Organism: $organism");
print p("Sequence Length: $sequence_length");
print p("Confidence Level: $confidence_level");

print end_html;

I have tried removing cgi use lines, then I get no error, but then server doesn't return anything.

Perlmonks site down - "we're performing some maintenance on our database"

r/perl

Published by /u/ContributionEastern7 on Wednesday 16 October 2024 20:35

Does anyone know how long perlmonks.org will be down?

submitted by /u/ContributionEastern7
[link] [comments]

I'm suddenly unable to run any Perl scripts under Cygwin. Every script I try to run crashes like this:

phil@TAICHI /cygdrive/h/bakE/new/virChecked
$ findFiles -s . -t /cygdrive/D/data-comp/text -u /cygdrive/E/new/virChecked/text -d -a .3
Can't load '/home/phil/perl5/lib/perl5/x86_64-cygwin-threads-multi/auto/Win32/File/File.dll' for module Win32::File: No such file or directory at /usr/lib/perl5/5.36/x86_64-cygwin-threads/DynaLoader.pm line 206.
 at /usr/local/bin/findFiles line 24.
Compilation failed in require at /usr/local/bin/findFiles line 24.
BEGIN failed--compilation aborted at /usr/local/bin/findFiles line 24.

phil@TAICHI /cygdrive/h/bakE/new/virChecked
$ pushd /home/phil/perl5/lib/perl5/x86_64-cygwin-threads-multi/auto/Win32/File/
~/perl5/lib/perl5/x86_64-cygwin-threads-multi/auto/Win32/File /cygdrive/h/bakE/new/virChecked

phil@TAICHI ~/perl5/lib/perl5/x86_64-cygwin-threads-multi/auto/Win32/File
$ ls -l File.dll
-r-xr-xr-x 1 phil None 178K Jul 14  2021 File.dll*

Sometimes perl won't open File.dll; sometimes it won't open IO.dll. In either case, the DLL is always exactly where Perl is looking for it, with world read privs; but Perl won't load it.

Line 206 of Dynaloader.pm is

my $libref = dl_load_file($file, $flags) or croak("Can't load '$file' for module $module: ".dl_error());

A comment near the start of Dynaloader says:

The load function that dl_load_file() calls may require an absolute pathname.

I can't find where dl_load_file() is defined. It isn't in Dynaloader.pm; and the only module Dynaloader includes is Config, which also doesn't have it, and includes no other files.

I suspect that some Perl module has changed, with the result that dl_load_file doesn't convert Cygwin absolute pathnames to Windows absolute pathnames. I tried reinstalling Perl 5.36.3-1, but it didn't help. I also made a new Cygwin installation and installed Perl 5.40, but it behaved the same way.

Questions:

  • Is anyone else currently able to use Perl in Cygwin using the lastest Cygwin packages?
  • Any idea what might have changed recently to make Cygwin Perl unable to use full Cygwin paths?
  • Where can I find a Cygwin perl distribution prior to Perl 5.32?

POSTSCRIPT added October 13: I've gotten a lot of comments, but not one person has yet answered the simple question of whether THEY currently have a working version of Cygwin Perl. Please, someone, if you have a recent Cygwin Perl that still works, say so.

How to Run a Perl Script in Linux — A Simple Guide for Beginners

Perl on Medium

Published by Noman Mohammad on Wednesday 16 October 2024 11:26

Are you new to Linux and wondering how to run a Perl script on your system? If you’re just starting with Linux or Perl, don’t worry…

How to use perltidy to reformat code in Visual Studio Code

Perl questions on StackOverflow

Published by horshack on Wednesday 16 October 2024 08:22

Windows, Visual Studio Code. I have installed the extension: "Perl Navigator" and perl is installed in my computer system, perltidy is installed. The code in a file is like this:

#!/usr/bin/perl
use strict;
use          warnings ;
use Params::Validate;

my $x     =4;
my    $y = "AB";

What can I do to reformat this code with perltidy with Visual Studio Code?

In vim I do this:

ESC :1,$!perltidy

I installed several extensions for Visual Studio Code but none of these tell me how to use them.

London Perl & Raku Workshop: 10 Days To Go

r/perl

Published by /u/leejo on Wednesday 16 October 2024 06:12

Net::SMTP with a BCC

r/perl

Published by /u/csdude5 on Wednesday 16 October 2024 06:01

I use Net::SMTP to send emails when a user requests data, and I have the email BCC'ed to my personal Gmail. But while it appears that the user does get the email (even when using Gmail), it's not showing up in my Gmail.

Any suggestions on what the problem might be?

I'm using these modules:

use Net::SMTP; use MIME::Lite; use Digest::MD5 qw(md5_hex); 

And this is the script:

$from = 'noreply@example.com'; $login_pass = 'blahblahblah'; $messageID = time(); $msg = MIME::Lite ->new ( From=> "Me <$from>", To=> "recipient@gmail.com", Bcc=> 'me@gmail.com', Subject=> "Subject", 'Message-ID'=> '<' . $messageID . '-' . md5_hex($from) . '-' . md5_hex($found_email) . '@example.com>', Type=> 'multipart/alternative' ); $msg->attach( Type => 'text/plain', Encoding=> 'quoted-printable', Data=> qq~ Plain text version of email ~ ); $msg->attach( Type => 'text/html', Data=> qq~ <b>HTML version of the email</b> ~ ); $msg->scrub(['x-mailer', 'Content-Disposition']); $smtp = Net::SMTP->new( 'mail.example.com', Port => 465, SSL => 1 ); $smtp->auth($from, $login_pass) or die('Could not authenticate'); $smtp->mail($from); if ($smtp->to($found_email)) { $smtp->data(); $smtp->datasend( $msg->as_string() ); $smtp->dataend(); } 
submitted by /u/csdude5
[link] [comments]

PSC – “Perl (re)branding ideas”?

r/perl

Published by /u/Drogoslaw_ on Tuesday 15 October 2024 22:42

The notes from the latest meeting of the Perl Steering Council mention:

We exchanged Perl (re)branding ideas with Olaf [Alders]. We will be keeping in touch on that front.

Does anyone here know whether this is only about the camel logo owned by O'Reilly or if there are some bigger changes coming (Perl 7?)?

submitted by /u/Drogoslaw_
[link] [comments]

regexec.c: Remove no-value-added function

Perl commits on GitHub

Published by khwilliamson on Tuesday 15 October 2024 16:28

regexec.c: Remove no-value-added function

This function merely calls an inline one.  Might as well not have any
indirection.

How to pass JSON using WWW::Mechanize in perl

Perl questions on StackOverflow

Published by Nilesh on Tuesday 15 October 2024 15:21

We are using WWW::Mechanize to send json data to our api.

My code is below.

#!/usr/local/bin/perl

use WWW::Mechanize;

sub get_csrf_token {
    my $sso = shift;
    my $referer = shift;
    my @cookie_items;
    my $rsp = $sso->get($referer);
    my $set_cookie = $rsp->header('set-cookie');
    if ($set_cookie =~ /csrftoken=(\S+);/) {
        push(@cookie_items, $1);
    }
    if ($set_cookie =~ /sessionid=(\S+);/) {
        push(@cookie_items, $1);
    }
    else {
        die 'Failed to get CSRF Token';
    }
    return @cookie_items;
}

my $sso = WWW::Mechanize->new(
        keep_alive  => 0,
        timeout     => 3000,
        stack_depth => 1,
        debug       => 1,
        verbose     => 1,
        key         => "/home/user/.athenz/key",
        cert        => "/home/user/.athenz/cert",
    );

my $referer = "https://myapi.domain.com/athenz/api/healthcheck/";
my @cookies = get_csrf_token($sso, $referer);
$sso->add_header('Referer' => $referer);
$sso->add_header('X-CSRFToken' => $cookies[0]);
$sso->add_header('Cookie' => "sessionid=$cookies[1]; csrftoken=$cookies[0]");

my %content = (
          'value' => '127.0.0.1',
          'key_name' => 'NTP_SERVERS'
);

my $response = $sso->put("https://myapi.domain.com/athenz/api/NTP_SERVERS/", \%content);

print "^^^^^^^^^^^^^^^^^^^^^^^^^\n";
print $response->code();
print "\n^^^^^^^^^^^^^^^^^^^^^^^^^\n";

its give me error Error PUTing https://myapi.domain.com/athenz/api/NTP_SERVERS/: Bad Request at /tmp/test.pm line 53

When I check server logs, its seems, the payload which I am sending, is deliver to server as HASH instead of json.

Below is apache logs.

[Mon Oct 07 18:32:27.987189 2024] [ssl:info] [pid 19745:tid 19745] [client 127.0.0.1:58372] AH01964: Connection to child 29 established (server myapi.domain.com:443)
[Mon Oct 07 18:32:27.987600 2024] [dumpio:trace7] [pid 19745:tid 19745] mod_dumpio.c(140): [client 127.0.0.1:58372] mod_dumpio: dumpio_in [init-blocking] 0 readbytes
[Mon Oct 07 18:32:27.987964 2024] [ssl:debug] [pid 19745:tid 19745] ssl_engine_kernel.c(2393): [client 127.0.0.1:58372] AH02043: SSL virtual host for servername myapi.domain.com found
[Mon Oct 07 18:32:27.992817 2024] [ssl:debug] [pid 19745:tid 19745] ssl_engine_kernel.c(2256): [client 127.0.0.1:58372] AH02041: Protocol: TLSv1.2, Cipher: ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)
[Mon Oct 07 18:32:27.992936 2024] [dumpio:trace7] [pid 19745:tid 19745] mod_dumpio.c(140): [client 127.0.0.1:58372] mod_dumpio: dumpio_in [getline-blocking] 0 readbytes
[Mon Oct 07 18:32:27.993929 2024] [dumpio:trace7] [pid 19745:tid 19745] mod_dumpio.c(63): [client 127.0.0.1:58372] mod_dumpio:  dumpio_in (data-TRANSIENT): 53 bytes
[Mon Oct 07 18:32:27.993964 2024] [dumpio:trace7] [pid 19745:tid 19745] mod_dumpio.c(103): [client 127.0.0.1:58372] mod_dumpio:  dumpio_in (data-TRANSIENT): PUT /athenz/api/NTP_SERVERS/ HTTP/1.1

[Mon Oct 07 18:32:27.994033 2024] [dumpio:trace7] [pid 19745:tid 19745] mod_dumpio.c(140): [client 127.0.0.1:58372] mod_dumpio: dumpio_in [getline-blocking] 0 readbytes
[Mon Oct 07 18:32:27.994047 2024] [dumpio:trace7] [pid 19745:tid 19745] mod_dumpio.c(63): [client 127.0.0.1:58372] mod_dumpio:  dumpio_in (data-TRANSIENT): 24 bytes
[Mon Oct 07 18:32:27.994056 2024] [dumpio:trace7] [pid 19745:tid 19745] mod_dumpio.c(103): [client 127.0.0.1:58372] mod_dumpio:  dumpio_in (data-TRANSIENT): TE: deflate,gzip;q=0.3

[Mon Oct 07 18:32:27.994065 2024] [dumpio:trace7] [pid 19745:tid 19745] mod_dumpio.c(140): [client 127.0.0.1:58372] mod_dumpio: dumpio_in [getline-blocking] 0 readbytes
[Mon Oct 07 18:32:27.994089 2024] [dumpio:trace7] [pid 19745:tid 19745] mod_dumpio.c(63): [client 127.0.0.1:58372] mod_dumpio:  dumpio_in (data-TRANSIENT): 23 bytes
[Mon Oct 07 18:32:27.994093 2024] [dumpio:trace7] [pid 19745:tid 19745] mod_dumpio.c(103): [client 127.0.0.1:58372] mod_dumpio:  dumpio_in (data-TRANSIENT): Connection: TE, close

[Mon Oct 07 18:32:27.994100 2024] [dumpio:trace7] [pid 19745:tid 19745] mod_dumpio.c(140): [client 127.0.0.1:58372] mod_dumpio: dumpio_in [getline-blocking] 0 readbytes
[Mon Oct 07 18:32:27.994104 2024] [dumpio:trace7] [pid 19745:tid 19745] mod_dumpio.c(63): [client 127.0.0.1:58372] mod_dumpio:  dumpio_in (data-TRANSIENT): 23 bytes
[Mon Oct 07 18:32:27.994123 2024] [dumpio:trace7] [pid 19745:tid 19745] mod_dumpio.c(103): [client 127.0.0.1:58372] mod_dumpio:  dumpio_in (data-TRANSIENT): Accept-Encoding: gzip

[Mon Oct 07 18:32:27.994127 2024] [dumpio:trace7] [pid 19745:tid 19745] mod_dumpio.c(140): [client 127.0.0.1:58372] mod_dumpio: dumpio_in [getline-blocking] 0 readbytes
[Mon Oct 07 18:32:27.994132 2024] [dumpio:trace7] [pid 19745:tid 19745] mod_dumpio.c(63): [client 127.0.0.1:58372] mod_dumpio:  dumpio_in (data-TRANSIENT): 45 bytes
[Mon Oct 07 18:32:27.994135 2024] [dumpio:trace7] [pid 19745:tid 19745] mod_dumpio.c(103): [client 127.0.0.1:58372] mod_dumpio:  dumpio_in (data-TRANSIENT): Host: myapi.domain.com

[Mon Oct 07 18:32:27.994139 2024] [dumpio:trace7] [pid 19745:tid 19745] mod_dumpio.c(140): [client 127.0.0.1:58372] mod_dumpio: dumpio_in [getline-blocking] 0 readbytes
[Mon Oct 07 18:32:27.994143 2024] [dumpio:trace7] [pid 19745:tid 19745] mod_dumpio.c(63): [client 127.0.0.1:58372] mod_dumpio:  dumpio_in (data-TRANSIENT): 84 bytes
[Mon Oct 07 18:32:27.994147 2024] [dumpio:trace7] [pid 19745:tid 19745] mod_dumpio.c(103): [client 127.0.0.1:58372] mod_dumpio:  dumpio_in (data-TRANSIENT): Referer: https://myapi.domain.com/athenz/api/healthcheck/

[Mon Oct 07 18:32:27.994151 2024] [dumpio:trace7] [pid 19745:tid 19745] mod_dumpio.c(140): [client 127.0.0.1:58372] mod_dumpio: dumpio_in [getline-blocking] 0 readbytes
[Mon Oct 07 18:32:27.994155 2024] [dumpio:trace7] [pid 19745:tid 19745] mod_dumpio.c(63): [client 127.0.0.1:58372] mod_dumpio:  dumpio_in (data-TRANSIENT): 32 bytes
[Mon Oct 07 18:32:27.994158 2024] [dumpio:trace7] [pid 19745:tid 19745] mod_dumpio.c(103): [client 127.0.0.1:58372] mod_dumpio:  dumpio_in (data-TRANSIENT): User-Agent: WWW-Mechanize/1.72

[Mon Oct 07 18:32:27.994185 2024] [dumpio:trace7] [pid 19745:tid 19745] mod_dumpio.c(140): [client 127.0.0.1:58372] mod_dumpio: dumpio_in [getline-blocking] 0 readbytes
[Mon Oct 07 18:32:27.994190 2024] [dumpio:trace7] [pid 19745:tid 19745] mod_dumpio.c(63): [client 127.0.0.1:58372] mod_dumpio:  dumpio_in (data-TRANSIENT): 128 bytes
[Mon Oct 07 18:32:27.994193 2024] [dumpio:trace7] [pid 19745:tid 19745] mod_dumpio.c(103): [client 127.0.0.1:58372] mod_dumpio:  dumpio_in (data-TRANSIENT): Cookie: sessionid=XXXXXXX; csrftoken=YYYYYYY

[Mon Oct 07 18:32:27.994198 2024] [dumpio:trace7] [pid 19745:tid 19745] mod_dumpio.c(140): [client 127.0.0.1:58372] mod_dumpio: dumpio_in [getline-blocking] 0 readbytes
[Mon Oct 07 18:32:27.994201 2024] [dumpio:trace7] [pid 19745:tid 19745] mod_dumpio.c(63): [client 127.0.0.1:58372] mod_dumpio:  dumpio_in (data-TRANSIENT): 19 bytes
[Mon Oct 07 18:32:27.994205 2024] [dumpio:trace7] [pid 19745:tid 19745] mod_dumpio.c(103): [client 127.0.0.1:58372] mod_dumpio:  dumpio_in (data-TRANSIENT): HASH(0x1d5b760):

[Mon Oct 07 18:32:27.994209 2024] [dumpio:trace7] [pid 19745:tid 19745] mod_dumpio.c(140): [client 127.0.0.1:58372] mod_dumpio: dumpio_in [getline-blocking] 0 readbytes
[Mon Oct 07 18:32:27.994213 2024] [dumpio:trace7] [pid 19745:tid 19745] mod_dumpio.c(63): [client 127.0.0.1:58372] mod_dumpio:  dumpio_in (data-TRANSIENT): 79 bytes
[Mon Oct 07 18:32:27.994217 2024] [dumpio:trace7] [pid 19745:tid 19745] mod_dumpio.c(103): [client 127.0.0.1:58372] mod_dumpio:  dumpio_in (data-TRANSIENT): X-CSRFToken: YYYYYYY

[Mon Oct 07 18:32:27.994223 2024] [core:debug] [pid 19745:tid 19745] protocol.c(1290): [client 127.0.0.1:58372 {YRA:127.0.0.1:58372, YPA:127.0.0.1:58372}] AH02426: Request header field name is malformed: HASH(0x1d5b760):, referer: https://myapi.domain.com/athenz/api/healthcheck/
[Mon Oct 07 18:32:27.994328 2024] [core:debug] [pid 19745:tid 19745] protocol.c(1482): [client 127.0.0.1:58372 {YRA:127.0.0.1:58372, YPA:127.0.0.1:58372}] AH00567: request failed: error reading the headers, referer: https://myapi.domain.com/athenz/api/healthcheck/

If I use same API with curl, it works fine and apache logs gives no error.

curl --cert ~/.athenz/cert --key ~/.athenz/key -H "Content-type: application/json" -H "X-CSRFToken: $TOKEN" --referer "https://myapi.domain.com/athenz/api/healthcheck/" --cookie "csrftoken=$TOKEN;sessionid=$SESSIONID;" "https://myapi.domain.com/athenz/api/NTP_SERVERS/" -X PUT -d '{"key_name": "NTP_SERVERS", "value": "98.139.133.27"}' -i
HTTP/1.1 200 OK
Date: Mon, 07 Oct 2024 18:26:50 GMT
P3P: policyref="https://policies.domain.com/w3c/p3p.xml", CP="CAO DSP COR CUR ADM DEV TAI PSA PSD IVAi IVDi CONi TELo OTPi OUR DELi SAMi OTRi UNRi PUBi IND PHY ONL UNI PUR FIN COM NAV INT DEM CNT STA POL HEA PRE LOC GOV"
Allow: GET, PUT, DELETE, HEAD, OPTIONS
X-Frame-Options: DENY
Vary: Cookie
Content-Length: 0
Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS
Access-Control-Allow-Credentials: true
X-Content-Type-Options: nosniff
Referrer-Policy: same-origin
Set-Cookie: csrftoken=YYYYYYYYYYY; Domain=.domain.com; expires=Mon, 06 Oct 2025 18:26:53 GMT; Max-Age=31449600; Path=/; SameSite=Lax
Set-Cookie: sessionid=XXXXXXXXXXXX; expires=Mon, 21 Oct 2024 18:26:53 GMT; HttpOnly; Max-Age=1209600; Path=/; SameSite=Lax
Cache-Control: private
Connection: close

The apache logs, which print the json I passed in the curl.

[Mon Oct 07 18:26:50.576736 2024] [dumpio:trace7] [pid 19725:tid 19725] mod_dumpio.c(140): [client 127.0.0.1:57073] mod_dumpio: dumpio_in [getline-blocking] 0 readbytes
[Mon Oct 07 18:26:50.935742 2024] [dumpio:trace7] [pid 19725:tid 19725] mod_dumpio.c(63): [client 127.0.0.1:57073] mod_dumpio:  dumpio_in (data-TRANSIENT): 53 bytes
[Mon Oct 07 18:26:50.935767 2024] [dumpio:trace7] [pid 19725:tid 19725] mod_dumpio.c(103): [client 127.0.0.1:57073] mod_dumpio:  dumpio_in (data-TRANSIENT): PUT /athenz/api/NTP_SERVERS/ HTTP/1.1

[Mon Oct 07 18:26:50.935821 2024] [dumpio:trace7] [pid 19725:tid 19725] mod_dumpio.c(140): [client 127.0.0.1:57073] mod_dumpio: dumpio_in [getline-blocking] 0 readbytes
[Mon Oct 07 18:26:50.935840 2024] [dumpio:trace7] [pid 19725:tid 19725] mod_dumpio.c(63): [client 127.0.0.1:57073] mod_dumpio:  dumpio_in (data-TRANSIENT): 31 bytes
[Mon Oct 07 18:26:50.935844 2024] [dumpio:trace7] [pid 19725:tid 19725] mod_dumpio.c(103): [client 127.0.0.1:57073] mod_dumpio:  dumpio_in (data-TRANSIENT): Host: myapi.domain.com

[Mon Oct 07 18:26:50.935848 2024] [dumpio:trace7] [pid 19725:tid 19725] mod_dumpio.c(140): [client 127.0.0.1:57073] mod_dumpio: dumpio_in [getline-blocking] 0 readbytes
[Mon Oct 07 18:26:50.935852 2024] [dumpio:trace7] [pid 19725:tid 19725] mod_dumpio.c(63): [client 127.0.0.1:57073] mod_dumpio:  dumpio_in (data-TRANSIENT): 24 bytes
[Mon Oct 07 18:26:50.935857 2024] [dumpio:trace7] [pid 19725:tid 19725] mod_dumpio.c(103): [client 127.0.0.1:57073] mod_dumpio:  dumpio_in (data-TRANSIENT): User-Agent: curl/8.7.1

[Mon Oct 07 18:26:50.935863 2024] [dumpio:trace7] [pid 19725:tid 19725] mod_dumpio.c(140): [client 127.0.0.1:57073] mod_dumpio: dumpio_in [getline-blocking] 0 readbytes
[Mon Oct 07 18:26:50.935867 2024] [dumpio:trace7] [pid 19725:tid 19725] mod_dumpio.c(63): [client 127.0.0.1:57073] mod_dumpio:  dumpio_in (data-TRANSIENT): 13 bytes
[Mon Oct 07 18:26:50.935871 2024] [dumpio:trace7] [pid 19725:tid 19725] mod_dumpio.c(103): [client 127.0.0.1:57073] mod_dumpio:  dumpio_in (data-TRANSIENT): Accept: */*

[Mon Oct 07 18:26:50.935875 2024] [dumpio:trace7] [pid 19725:tid 19725] mod_dumpio.c(140): [client 127.0.0.1:57073] mod_dumpio: dumpio_in [getline-blocking] 0 readbytes
[Mon Oct 07 18:26:50.935880 2024] [dumpio:trace7] [pid 19725:tid 19725] mod_dumpio.c(63): [client 127.0.0.1:57073] mod_dumpio:  dumpio_in (data-TRANSIENT): 43 bytes
[Mon Oct 07 18:26:50.935883 2024] [dumpio:trace7] [pid 19725:tid 19725] mod_dumpio.c(103): [client 127.0.0.1:57073] mod_dumpio:  dumpio_in (data-TRANSIENT): Referer: https://myapi.domain.com/api/healthcheck/

[Mon Oct 07 18:26:50.935887 2024] [dumpio:trace7] [pid 19725:tid 19725] mod_dumpio.c(140): [client 127.0.0.1:57073] mod_dumpio: dumpio_in [getline-blocking] 0 readbytes
[Mon Oct 07 18:26:50.935890 2024] [dumpio:trace7] [pid 19725:tid 19725] mod_dumpio.c(63): [client 127.0.0.1:57073] mod_dumpio:  dumpio_in (data-TRANSIENT): 128 bytes
[Mon Oct 07 18:26:50.935894 2024] [dumpio:trace7] [pid 19725:tid 19725] mod_dumpio.c(103): [client 127.0.0.1:57073] mod_dumpio:  dumpio_in (data-TRANSIENT): Cookie: csrftoken=YYYYYYYY;sessionid=XXXXXXX;

[Mon Oct 07 18:26:50.935908 2024] [dumpio:trace7] [pid 19725:tid 19725] mod_dumpio.c(140): [client 127.0.0.1:57073] mod_dumpio: dumpio_in [getline-blocking] 0 readbytes
[Mon Oct 07 18:26:50.935913 2024] [dumpio:trace7] [pid 19725:tid 19725] mod_dumpio.c(63): [client 127.0.0.1:57073] mod_dumpio:  dumpio_in (data-TRANSIENT): 32 bytes
[Mon Oct 07 18:26:50.935917 2024] [dumpio:trace7] [pid 19725:tid 19725] mod_dumpio.c(103): [client 127.0.0.1:57073] mod_dumpio:  dumpio_in (data-TRANSIENT): Content-type: application/json

[Mon Oct 07 18:26:50.935922 2024] [dumpio:trace7] [pid 19725:tid 19725] mod_dumpio.c(140): [client 127.0.0.1:57073] mod_dumpio: dumpio_in [getline-blocking] 0 readbytes
[Mon Oct 07 18:26:50.935926 2024] [dumpio:trace7] [pid 19725:tid 19725] mod_dumpio.c(63): [client 127.0.0.1:57073] mod_dumpio:  dumpio_in (data-TRANSIENT): 79 bytes
[Mon Oct 07 18:26:50.935930 2024] [dumpio:trace7] [pid 19725:tid 19725] mod_dumpio.c(103): [client 127.0.0.1:57073] mod_dumpio:  dumpio_in (data-TRANSIENT): X-CSRFToken: YYYYYYYYY

[Mon Oct 07 18:26:50.935934 2024] [dumpio:trace7] [pid 19725:tid 19725] mod_dumpio.c(140): [client 127.0.0.1:57073] mod_dumpio: dumpio_in [getline-blocking] 0 readbytes
[Mon Oct 07 18:26:50.935937 2024] [dumpio:trace7] [pid 19725:tid 19725] mod_dumpio.c(63): [client 127.0.0.1:57073] mod_dumpio:  dumpio_in (data-TRANSIENT): 20 bytes
[Mon Oct 07 18:26:50.935942 2024] [dumpio:trace7] [pid 19725:tid 19725] mod_dumpio.c(103): [client 127.0.0.1:57073] mod_dumpio:  dumpio_in (data-TRANSIENT): Content-Length: 91

[Mon Oct 07 18:26:50.935946 2024] [dumpio:trace7] [pid 19725:tid 19725] mod_dumpio.c(140): [client 127.0.0.1:57073] mod_dumpio: dumpio_in [getline-blocking] 0 readbytes
[Mon Oct 07 18:26:50.935949 2024] [dumpio:trace7] [pid 19725:tid 19725] mod_dumpio.c(63): [client 127.0.0.1:57073] mod_dumpio:  dumpio_in (data-TRANSIENT): 2 bytes
[Mon Oct 07 18:26:50.935953 2024] [dumpio:trace7] [pid 19725:tid 19725] mod_dumpio.c(103): [client 127.0.0.1:57073] mod_dumpio:  dumpio_in (data-TRANSIENT):

[Mon Oct 07 18:26:50.937521 2024] [dumpio:trace7] [pid 19725:tid 19725] mod_dumpio.c(140): [client 127.0.0.1:57073] mod_dumpio: dumpio_in [readbytes-blocking] 91 readbytes
[Mon Oct 07 18:26:50.937532 2024] [dumpio:trace7] [pid 19725:tid 19725] mod_dumpio.c(63): [client 127.0.0.1:57073] mod_dumpio:  dumpio_in (data-TRANSIENT): 91 bytes
[Mon Oct 07 18:26:50.937537 2024] [dumpio:trace7] [pid 19725:tid 19725] mod_dumpio.c(103): [client 127.0.0.1:57073] mod_dumpio:  dumpio_in (data-TRANSIENT): {"key_name": "NTP_SERVERS", "value": "98.139.133.27"}
[Mon Oct 07 18:26:50.937558 2024] [ssl:info] [pid 19725:tid 19725] [client 127.0.0.1:57073 {YRA:127.0.0.1:57073, YPA:127.0.0.1:57073}] AH02221: Requesting connection re-negotiation, referer: https://myapi.domain.com/api/healthcheck/

How can I make sure, perl script pass json data to the apache server? I tried setting Content-Type: application/json, that didnt work.

perlapi: Rmv extraneous minus sign

Perl commits on GitHub

Published by khwilliamson on Tuesday 15 October 2024 14:54

perlapi: Rmv extraneous minus sign

Mojolicious::Plugin::OpenAPI 404 error when posting

Perl questions on StackOverflow

Published by smith on Tuesday 15 October 2024 14:01

I am running this snippet of code from the module synopsis using strawberry Perl :

use Mojolicious::Lite;
 
# Because the route name "echo" matches the "x-mojo-name", this route
# will be moved under "basePath", resulting in "POST /api/echo"
post "/echo" => sub {
 
  # Validate input request or return an error document
  my $c = shift->openapi->valid_input or return;
 
  # Generate some data
  my $data = {body => $c->req->json};
 
  # Validate the output response and render it to the user agent
  # using a custom "openapi" handler.
  $c->render(openapi => $data);
}, "echo";
 
# Load specification and start web server
plugin OpenAPI => {url => "data:///swagger.yaml"};
app->start;
 
__DATA__
@@ swagger.yaml
swagger: "2.0"
info: { version: "0.8", title: "Echo Service" }
schemes: ["https"]
basePath: "/api"
paths:
  /echo:
   post:
     x-mojo-name: "echo"
     parameters:
     - { in: "body", name: "body", schema: { type: "object" } }
     responses:
       200:
         description: "Echo response"
         schema: { type: "object" } 

Then run the script as a daemon which listen on port 3000 after that i am running Curl as the below from the same machine

curl -X POST http://127.0.0.1:3000/api/echo -H "Content-Type : application/json" -d "{ \"key\" : \"value\" }"

my expection to render the __DATA__ section but i am getting this error

{"errors":[{"message":"Expected  - got *\/*.","path":"\/header\/Accept"}],"status":400}

any idea what could be the problem ?

fix authors after previous commit

Perl commits on GitHub

Published by iabyn on Tuesday 15 October 2024 09:49

fix authors after previous commit

Table subset searching with a list and DBIx::Class

dev.to #perl

Published by Paul Cochrane 🇪🇺 on Monday 14 October 2024 22:00

When searching for a subset of rows in a database table by using a list of entries in one of its columns, one can use the WHERE column_name IN list syntax in an SQL query. How to do this using DBIx::Class wasn’t obvious to me; at least, not by reading the docs. I worked it out eventually. Here’s what I learned.

This won’t be new to many people, but it was new to me and I couldn’t find the part of the docs where this is discussed, so I thought I’d write it up here for my future self to find.

Subset selecting in SQL

Imagine this situation: you have a database table from which you want to select a subset of its rows depending upon known values of one of its columns. Take this data for example, which represents possible failure states in an application:

id name severity
0 Ok 0
1 Warning 1
2 Critical 2
3 Error 3
4 Degradation 1
5 Mismatch 1
6 Contamination 2
7 Unknown -1

Now imagine that not all parts of the application use all failure states. Some only need to use Ok, Warning, Critical, and Error, while others use Ok, Degradation, Mismatch and Unknown. How does one pull out the rows only of interest to that specific part of the application? One way to do this would be like so (note: I’m still a bit of an SQL noob, so be nice to me):

SELECT * FROM failure_states WHERE name IN ('Ok', 'Degradation', 'Mismatch', 'Unknown');

That’s cool. Now, I’ve been working more with DBIx::Class recently, having spent the last several years working almost only with Django and its ORM, hence I’m also a DBIx::Class noob. Anyway, I wanted to do this lookup from DBIx::Class and only stumbled across the example mentioned in the search docs for DBIx::Class::ResultSet, i.e. this bit:

my @cds = $cd_rs->search({ year => 2001 }); # "... WHERE year = 2001"
my $new_rs = $cd_rs->search({ year => 2005 });

my $new_rs = $cd_rs->search([{ year => 2005 }, { year => 2004 }]);
               # year = 2005 OR year = 2004

Using this pattern to solve the problem above yields code like this:

my @states = FailureState->search(
    [
        { name => 'Ok' },
        { name => 'Degradation' },
        { name => 'Mismatch' },
        { name => 'Unknown' },
    ]
);

That, as one might say in the New Zealand vernacular, is fugling uckly. Putting things another way, there’s a lot of duplication here, which doesn’t make this solution DRY and it’s not a pattern that would scale well. It works, but surely there’s a better way, right?

Simpler subsets in DBIx::Class

It turns out that yes, there is a better way, and as is often the case, I found an appropriate answer on StackOverflow. Also, because this is Perl, there is more than one way to do it. For instance with the = operator within a search() method call:

my @state_names = qw(Ok Degradation Mismatch Unknown);
my @states = FailureState->search(
    {
        name => { '=' => [@state_names] }
    }
);

This probably does something like WHERE name = $state_name in the background … I guess? I’m not sure about the details here, so I’m going to be content with waving my arms as an explanation.

Alternatively, one can use a syntax reminiscent of the WHERE column_name IN list syntax:

my @state_names = qw(Ok Degradation Mismatch Unknown);
my @states = FailureState->search(
    {
        name => { -in => [@state_names] }
    }
);

But why use several lines when only two are sufficient? One can be more direct and pass an arrayref:

my @state_names = qw(Ok Degradation Mismatch Unknown);
my @states = FailureState->search( { name => \@state_names } );

Nice!

Good enough for now

I’m sure there are other and better ways of doing this. Even so, this change has simplified my code nicely. Also, I learned something new today, which was cool :-)

clarify the comparison between 'our' and 'use vars'

Perl commits on GitHub

Published by book on Monday 14 October 2024 17:53

clarify the comparison between 'our' and 'use vars'

Fixes GH #22424

Perl Weekly #690 - London Perl & Raku Workshop 2024

dev.to #perl

Published by Gabor Szabo on Monday 14 October 2024 06:43

Originally published at Perl Weekly 690

Hi there,

Happy Hacking everyone !!!

I hope you are busy contributing during this year Hacktoberfest. We are half way through already but still plenty of time left to kickstart if not done already.

How about LPW 2024?

Well it is less than 2 weeks before the much awaited London Perl & Raku Workshop 2024 begins the fun. I am very happy to see the support of Perl community in general. It is great to see regular names in the list of sponsors, specially my current employer Oleeo as Gold sponsor. Thank you, Lee Johnson, for all the hardwork, managing the event so smoothly so far. I am confident it would be a memorable event for everyone.

Those who are planning to attend the event, there would be Pre Workshop Social and Post Workshop Social. Please register your details asap. I have once attended pre workshop social in the past as the usual venue is not my favourite spot. Having said, I am planning to break the tradition this year and planning to attend post social workshop. How can I miss the opportunity to meet my techie friends.

Have you seen the favourite talks list?

I am personally looking forward to attend the talks e.g. Perl in 2030, Cloudy Perl, how it looks now, A modern introduction to XS. Also my own talk, What's new in Perl v5.40?. I happy to see the some familiar names shown interest in my talk. I can't wait to present my talk.

I am also looking forward to meet some of my techie friends after a long time. Recently I found out one coming all the way from Canada. I am wondering if anyone coming from Japan. In the past, we always had speaker from Japan. I hope to see the familiar face this time too. Anyone from Germany? We will all find out first thing at the registration desk on the day.

As the October arrived, it also brought the dull weather with it. I don't have good memory about it. I hope it passes without creating any havoc. You take extra care of your health, specially mental and enjoy rest of the newsletter.

--
Your editor: Mohammad Sajid Anwar.

Announcements

Weather::OWM released on CPAN

A new module, Weather::ORM just arrived. The OpenWeather API has a Free tier with both current weather and forecast, which makes the module useful to anyone interested in fetching weather for any location.

Articles

This week in PSC (163) | 2024-10-10

Olaf Alders joined this week PSC meeting exchanged ideas.

Why The Perl and Raku Foundation Supports The Open Source Pledge

The Open Source Pledge consists of companies with a shared commitment to paying the maintainers of the open source software they consume, therefore aims to help address sustainability challenges facing the Open Source community.

How to create a parallel echo server using goroutines in SPVM?

Create a parallel echo server using SPVM::IO::Socket::IP and goroutines, channels, select in SPVM::Go.

How to generate an executable file for an AI program using SPVM ?

Wouldn't you like to output a single executable file from your AI program? Then, you can run the AI ​​program just by copying the executable file to the Raspberry Pi.

wxPerl Revival

This is the beginning of wxPerl revival. Please do support the initiative.

Web

London Perl & Raku Workshop 2024 Gold Sponsor: Oleeo

Oleeo is an award-winning provider of innovative talent acquisition technology. Built using intelligent automation and machine learning, Oleeo’s platform helps companies discover unlimited sourcing potential to attract, engage and hire amazing, diverse teams that change the world for the better.

London Perl & Raku Workshop 2024 Silver Sponsors

Geekuni can give software developers with no previous Perl experience the training they need, as they need it. Geizhals Preisvergleich is one of the largest product and price comparison platforms in the German-speaking area.

Grants

Maintaining Perl 5 Core (Dave Mitchell): September 2024

The Weekly Challenge

The Weekly Challenge by Mohammad Sajid Anwar will help you step out of your comfort-zone. You can even win prize money of $50 by participating in the weekly challenge. We pick one champion at the end of the month from among all of the contributors during the month, thanks to the sponsor Lance Wicks.

The Weekly Challenge - 291

Welcome to a new week with a couple of fun tasks "Middle Index" and "Poker Hand Rankings". If you are new to the weekly challenge then why not join us and have fun every week. For more information, please read the FAQ.

RECAP - The Weekly Challenge - 290

Enjoy a quick recap of last week's contributions by Team PWC dealing with the "Double Exist" and "Luhn's Algorithm" tasks in Perl and Raku. You will find plenty of solutions to keep you busy.

TWC290

Compact solutions in Perl as always and self explanatory. You really don't want to miss it.

Finding Double Existence and Applying Luhn's Algorithm

Simple yet elegant approach in Perl and Go. Great work, keep sharing.

Luhn's Existence

Interesting way to deal with edge case using the power of Raku. And on top, get the complete official word on each feature used.

Two Times Zero is Zero

You get nice story to start with and then comes the technical discussion. It is engaging yet, thanks for sharing.

Perl Weekly Challenge: Week 290

Line-by-line discussion is a cool way to get the end result. Keep it up great work.

Perl Weekly Challenge 290: Double Exist

As per the tradition, we got side by side implementation in Perl and Raku. Plenty for both fans, keep the tradition alive.

Perl Weekly Challenge 290: Luhn's Algorithm

Real life story behind Luhn's algorithm. Thanks for sharing the story with us. Great work.

arrays and numbers

Simple loop in Raku is enough to get this week task done and self explanatory too. We also have bonus solutions in Java, Python and PostgreSQL.

Perl Weekly Challenge 290

In-house Perl one-liner expert sharing the quality implementation. Keep it up great work.

Take Me to the Luhn and Back

Smart use of CPAN to get a compact solution in Perl. Simple love the detailed discussion. Keep sharing the knowledge with us.

Double Your Pleasure, Double Your Luhn

Musical background to the weekly challenge is always fun. Following which we get the thorough discussion of implementation in Perl, Raku, Python and Elixir. Highly recommended.

Double existence and checking the payload

A verbose approach to make it easy to read and follow. DIY tool is the icing on the cake. Well done.

The Weekly Challenge - 290

Old school double loops with detailed comments. Keep it up great work.

The Weekly Challenge #290

We got another musical solution. I just love the musical theme. Keep sharing knowledge.

Double Luhn

Postscript is one language that I find very fascinating and when we get the detailed narration then it becomes so easy to follow. Highly recommended.

Seeing Double, Twice!

Two in a row, what a pleasant surprise. Thanks for the quality blog post. Please keep sharing.

Double Luhn

Like always, the post is dedicated to Python fans. Plenty for Perl fans to learn. Keep it up great work.

Rakudo

2024.41 KnowLite

Weekly collections

NICEPERL's lists

Great CPAN modules released last week.

Events

Toronto Perl Mongers monthly meeting

October 24, 2024, Virtual event

London Perl and Raku Workshop

October 26, 2024, in London, UK

Boston.pm monthly meeting

November 12, 2024, Virtual event

Purdue Perl Mongers

November 13, 2024, Virtual event

You joined the Perl Weekly to get weekly e-mails about the Perl programming language and related topics.

Want to see more? See the archives of all the issues.

Not yet subscribed to the newsletter? Join us free of charge!

(C) Copyright Gabor Szabo
The articles are copyright the respective authors.

The examples used here are from the weekly challenge problem statement and demonstrate the working solution.

Part 1: Double Exist

You are given an array of integers, @ints. Write a script to find if there exist two indices $i and $j such that:

  1. $i≠$j
  2. 0 $i < size @ints and 0 $j < size @ints
  3. $ints[$i] = 2 $ints[$j]

The majority of the work can be done in a few lines. If there is a more elegant way to do this, it escaped me when I was writing this code!

nested loop to determine if the conditions hold 1 ⟩≡


sub double_exist{
my(@a) = @_;
do{
my $i = $_;
do{
my $j = $_;
if($i != $j){
return 1 if $a[$i] == 2 * $a[$j];
}
} for 0 .. @a - 1;
} for 0 .. @a - 1;
return 0;
}

Fragment referenced in 2.

The rest of the code just tests this function.

"ch-1.pl" 2


preamble 3
nested loop to determine if the conditions hold 1
main 4

preamble 3 ⟩≡


use v5.40;

Fragment referenced in 2, 7.

main 4 ⟩≡


MAIN:{
say double_exist 6, 2, 3, 3;
say double_exist 3, 1, 4, 13;
say double_exist 2, 1, 4, 2;
}

Fragment referenced in 2.

Sample Run
$ perl perl/ch-1.pl 
1 
0 
1
    

Part 2: Luhn’s Algorithm

You are given a string $str containing digits (and possibly other characters which can be ignored). The last digit is the payload; consider it separately. Counting from the right, double the value of the first, third, etc. of the remaining digits. For each value now greater than 9, sum its digits. The correct check digit is that which, added to the sum of all values, would bring the total mod 10 to zero. Return true if and only if the payload is equal to the correct check digit.

This can also be done in relatively few lines. There are no real special cases here.

loop and evaluate the check sum 5 ⟩≡


sub luhn{
my($digits) = @_;
my @digits = $digits =~ m/([0-9])/g;
my $sum = 0;
my $check = pop @digits;
{
my $x = pop @digits;
my $y = pop @digits;
if(defined $x && defined $y){
$sum += $y + sum_digits 2 * $x;
}
else{
$sum += sum_digits 2 * $x;
}
redo if @digits;
}
return 1 if 0 == ($sum + $check) % 10;
return 0;
}

Fragment referenced in 7.

For convenience we’ll put the summing of digits for numbers > 10 in a separate function.

sum digits for numbers > 10 6 ⟩≡


sub sum_digits{
my($x) = @_;
if($x >= 10){
my @a = split //, $x;
return $a[0] + $a[1];
}
return $x;
}

Fragment referenced in 7.

The rest of the code drives some tests.

"ch-2.pl" 7


preamble 3
sum digits for numbers > 10 6
loop and evaluate the check sum 5
main 8

main 8 ⟩≡


MAIN:{
say luhn q/17893729974/;
say luhn q/4137 8947 1175 5904/;
say luhn q/4137 8974 1175 5904/;
}

Fragment referenced in 7.

Sample Run
$ perl perl/ch-2.pl 
1 
1 
0
    

References

The Weekly Challenge 290
Generated Code

BLOG: The Weekly Challenge #049

The Weekly Challenge

Published on Monday 14 October 2024 03:27

This is my second blog for The Weekly Challenge. I am only able to participate, thanks to Ryan Thompson for helping me with the Perl and Raku reviews. I am going for Perl solutions first then will try to translate it into Raku next. I believe in coding to learn the language. With so many Raku experts around, I am not shy throwing questions up. I am now going to share my experience doing “The Weekly Challenge - 049”.

Scheme

The Weekly Challenge

Published on Monday 14 October 2024 03:27

As you know, The Weekly Challenge, primarily focus on Perl and Raku. During the Week #018, we received solutions to The Weekly Challenge - 018 by Orestis Zekai in Python. It was pleasant surprise to receive solutions in something other than Perl and Raku. Ever since regular team members also started contributing in other languages like Ada, APL, Awk, BASIC, Bash, Bc, Befunge-93, Bourne Shell, BQN, Brainfuck, C3, C, CESIL, Chef, COBOL, Coconut, C Shell, C++, Clojure, Crystal, D, Dart, Dc, Elixir, Elm, Emacs Lisp, Erlang, Excel VBA, F#, Factor, Fennel, Fish, Forth, Fortran, Gembase, GNAT, Go, GP, Groovy, Haskell, Haxe, HTML, Hy, Idris, IO, J, Janet, Java, JavaScript, Julia, K, Korn Shell, Kotlin, Lisp, Logo, Lua, M4, Maxima, Miranda, Modula 3, MMIX, Mumps, Myrddin, Nelua, Nim, Nix, Node.

Coconut

The Weekly Challenge

Published on Monday 14 October 2024 03:27

As you know, The Weekly Challenge, primarily focus on Perl and Raku. During the Week #018, we received solutions to The Weekly Challenge - 018 by Orestis Zekai in Python. It was pleasant surprise to receive solutions in something other than Perl and Raku. Ever since regular team members also started contributing in other languages like Ada, APL, Awk, BASIC, Bash, Bc, Befunge-93, Bourne Shell, BQN, Brainfuck, C3, C, CESIL, Chef, COBOL, Coconut, C Shell, C++, Clojure, Crystal, D, Dart, Dc, Elixir, Elm, Emacs Lisp, Erlang, Excel VBA, F#, Factor, Fennel, Fish, Forth, Fortran, Gembase, GNAT, Go, GP, Groovy, Haskell, Haxe, HTML, Hy, Idris, IO, J, Janet, Java, JavaScript, Julia, K, Korn Shell, Kotlin, Lisp, Logo, Lua, M4, Maxima, Miranda, Modula 3, MMIX, Mumps, Myrddin, Nelua, Nim, Nix, Node.

Awk

The Weekly Challenge

Published on Monday 14 October 2024 03:27

As you know, The Weekly Challenge, primarily focus on Perl and Raku. During the Week #018, we received solutions to The Weekly Challenge - 018 by Orestis Zekai in Python. It was pleasant surprise to receive solutions in something other than Perl and Raku. Ever since regular team members also started contributing in other languages like Ada, APL, Awk, BASIC, Bash, Bc, Befunge-93, Bourne Shell, BQN, Brainfuck, C3, C, CESIL, Chef, COBOL, Coconut, C Shell, C++, Clojure, Crystal, D, Dart, Dc, Elixir, Elm, Emacs Lisp, Erlang, Excel VBA, F#, Factor, Fennel, Fish, Forth, Fortran, Gembase, GNAT, Go, GP, Groovy, Haskell, Haxe, HTML, Hy, Idris, IO, J, Janet, Java, JavaScript, Julia, K, Korn Shell, Kotlin, Lisp, Logo, Lua, M4, Maxima, Miranda, Modula 3, MMIX, Mumps, Myrddin, Nelua, Nim, Nix, Node.

Mumps

The Weekly Challenge

Published on Monday 14 October 2024 03:27

As you know, The Weekly Challenge, primarily focus on Perl and Raku. During the Week #018, we received solutions to The Weekly Challenge - 018 by Orestis Zekai in Python. It was pleasant surprise to receive solutions in something other than Perl and Raku. Ever since regular team members also started contributing in other languages like Ada, APL, Awk, BASIC, Bash, Bc, Befunge-93, Bourne Shell, BQN, Brainfuck, C3, C, CESIL, Chef, COBOL, Coconut, C Shell, C++, Clojure, Crystal, D, Dart, Dc, Elixir, Elm, Emacs Lisp, Erlang, Excel VBA, F#, Factor, Fennel, Fish, Forth, Fortran, Gembase, GNAT, Go, GP, Groovy, Haskell, Haxe, HTML, Hy, Idris, IO, J, Janet, Java, JavaScript, Julia, K, Korn Shell, Kotlin, Lisp, Logo, Lua, M4, Maxima, Miranda, Modula 3, MMIX, Mumps, Myrddin, Nelua, Nim, Nix, Node.

What's new on CPAN - September 2024

perl.com

Published on Monday 14 October 2024 02:07

Welcome to “What’s new on CPAN”, a curated look at last month’s new CPAN uploads for your reading and programming pleasure. Enjoy!

APIs & Apps

Config & Devops

Data

Development & Version Control

Science & Mathematics

Web

Other

What's new on CPAN - August 2024

perl.com

Published on Monday 14 October 2024 01:53

Welcome to “What’s new on CPAN”, a curated look at last month’s new CPAN uploads for your reading and programming pleasure. Enjoy!

APIs & Apps

Config & Devops

Data

Development & Version Control

Language & International

Science & Mathematics

  • Bio::EnsEMBL (ABECKER) provides access to EnsEMBL genomic databases

Web

Other

(dxvii) 9 great CPAN modules released last week

Niceperl

Published by Unknown on Sunday 13 October 2024 13:06

Updates for great CPAN modules released last week. A module is considered great if its favorites count is greater or equal than 12.

  1. CryptX - Cryptographic toolkit
    • Version: 0.082 on 2024-10-07, with 51 votes
    • Previous CPAN version: 0.081 was 29 days before
    • Author: MIK
  2. HTTP::Message - HTTP style message (base class)
    • Version: 7.00 on 2024-10-07, with 67 votes
    • Previous CPAN version: 6.46 was 4 months, 11 days before
    • Author: OALDERS
  3. Kelp - A web framework light, yet rich in nutrients.
    • Version: 2.19 on 2024-10-10, with 44 votes
    • Previous CPAN version: 2.17 was 3 months, 4 days before
    • Author: BRTASTIC
  4. meta - meta-programming API
    • Version: 0.011 on 2024-10-08, with 13 votes
    • Previous CPAN version: 0.010 was 7 days before
    • Author: PEVANS
  5. namespace::autoclean - Keep imports out of your namespace
    • Version: 0.31 on 2024-10-12, with 27 votes
    • Previous CPAN version: 0.29 was 5 years, 1 month, 19 days before
    • Author: ETHER
  6. Parser::MGC - build simple recursive-descent parsers
    • Version: 0.22 on 2024-10-11, with 12 votes
    • Previous CPAN version: 0.21 was 2 years, 7 months, 16 days before
    • Author: PEVANS
  7. PPR - Pattern-based Perl Recognizer
    • Version: 0.001010 on 2024-10-07, with 22 votes
    • Previous CPAN version: 0.001009 was 3 months, 11 days before
    • Author: DCONWAY
  8. SPVM - The SPVM Language
    • Version: 0.990020 on 2024-10-11, with 33 votes
    • Previous CPAN version: 0.990016 was 7 days before
    • Author: KIMOTO
  9. URI - Uniform Resource Identifiers (absolute and relative)
    • Version: 5.30 on 2024-10-08, with 115 votes
    • Previous CPAN version: 5.29 was 1 month, 3 days before
    • Author: OALDERS

wxPerl Revival

dev.to #perl

Published by Johan Vromans on Saturday 12 October 2024 19:09

For several years now, development and support of wxPerl, the interface library between Perl and wxWidgets, has stalled. The latest release was based on Perl 5.16 and wxWidgets 2.9.

Meanwhile some active users have made attempts to port wxPerl to newer versions of Perl and wxWidgets, with varying results. Microsoft Windows and Apple macOS provide additional challenges.

I believe in user-friendly desktop based GUI applications written in Perl and wxPerl is an excellent tool to develop these applications that are deployable across different desktop platforms. I hate to see wxPerl rusting away in the archives.

If you are using wxPerl and want to keep using it with recent
versions of Perl and wxWidgets, please join the mailing list.

As a start, I've set up a new, independent repo for wxPerl on GitHub.

It currently has two branches: wx30 and master.

Branch wx30 contains an updated version of the last 'official' release 0.9932, fixed for modern Perl and wxWidgets 3.0. I have released it on GitHub as Wx-0.9933.

The master branch has been updated with all necessary changes for wxWidgets 3.2. Also some constants and methods have been added to deploy some 3.2 functionality. I have released it on GitHub as Wx-3.001. More will be added in the future but will require help from Perl/XS experts.

Yes, you read that right. Just install Straberry Perl and gcc will be properly installed in your Windows machine.

Double Luhn

dev.to #perl

Published by Simon Green on Saturday 12 October 2024 03:11

Weekly Challenge 290

Each week Mohammad S. Anwar sends out The Weekly Challenge, a chance for all of us to come up with solutions to two weekly tasks. My solutions are written in Python first, and then converted to Perl. It's a great way for us all to practice some coding.

Challenge, My solutions

Task 1: Double Exist

Tasks

You are given an array of integers, @ints.

Write a script to find if there exist two indices $i and $j such that:

  1. $i != $j
  2. 0 <= ($i, $j) < scalar @ints
  3. $ints[$i] == 2 * $ints[$j]

My solution

This seems relatively straight forward, but there is a massive gotcha that hopefully other Team PWC members also noticed. For this task, I loop through the list and see if a value that is twice its value exist.

However, if the value is '0' (and thus 0 × 2 = 0), I need to check that there were at least two zeros in the list.

def double_exists(ints: list) -> bool:

    for i in ints:
        if i * 2 in ints:
            if i != 0 or ints.count(0) > 1:
                return True

    return False

Examples

$ ./ch-1.py 6 2 3 3
true

$ ./ch-1.py 3 1 4 13
false

$ ./ch-1.py 2 1 4 2
true

$ ./ch-1.py 1 3 0
false

$ ./ch-1.py 1 0 3 0
true

Task 2: Luhn’s Algorithm

Task

You are given a string $str containing digits (and possibly other characters which can be ignored). The last digit is the payload; consider it separately. Counting from the right, double the value of the first, third, etc. of the remaining digits.

For each value now greater than 9, sum its digits.

The correct check digit is that which, added to the sum of all values, would bring the total mod 10 to zero.

Return true if and only if the payload is equal to the correct check digit.

My solution

I start this task by removing non-digit characters from the string, and turn the reversed string into a list of integers.

I then use the supplied formula, alternating between adding the value to count or multiplying it by two and removing 9. If the resulting count is divisible by 10, I return True, otherwise I return False.

def luhn_algorithm(s: str) -> bool:
    s = re.sub('[^0-9]', '', s)
    ints = [int(n) for n in s[::-1]]

    count = 0
    for pos, i in enumerate(ints):
        if pos % 2 == 1:
            i *= 2
            if i > 9:
                i -= 9
        count += i
    return count % 10 == 0

Examples

$ ./ch-2.py  17893729974
true

$ ./ch-2.py  "4137 8947 1175 5904"
true

$ ./ch-2.py "4137 8974 1175 5904"
false

Finding Double Existence and Applying Luhn's Algorithm

dev.to #perl

Published by André Plöger on Friday 11 October 2024 19:50

In this article, we will address two engaging tasks from the Perl Weekly Challenge #290: checking for double existence in an array and implementing Luhn's Algorithm for validation. We'll implement solutions in both Perl and Go.

Table of Contents

  • Double Existence
  • Luhn's Algorithm
  • Conclusion

Double Existence

The first task involves finding if there exist two indices $i and $j such that:

1. $i != $j
2. 0 <= ($i, $j) < scalar @ints
3. $ints[i] = 2 * $ints[j]

Task Description

Input: An array of integers, @ints.

Output: true if the condition is met; otherwise, false.

Examples:

Input: @ints = (6, 2, 3, 3)
Output: true

For $i = 0, $j = 2
$ints[$i] = 6 => 2 * 3 =>  2 * $ints[$j]
Input: @ints = (3, 1, 4, 13)
Output: false
Input: @ints = (2, 1, 4, 2)
Output: true

For $i = 2, $j = 3
$ints[$i] = 4 => 2 * 2 =>  2 * $ints[$j]

Solution

Perl Implementation
In the Perl implementation, we use a hash to track seen integers and check if either half or double of the current number exists in the hash.

sub double_exist {
    my %seen;

    foreach my $num (@_) {
        return 1 if exists $seen{$num / 2} || exists $seen{$num * 2};
        $seen{$num} = 1;
    }

    return 0;
}

Go Implementation
The Go implementation follows a similar logic, using a map to keep track of unique integers.

func doubleExist(ints []int) bool {
    seen := make(map[int]bool)

    for _, num := range ints {
        if (num%2 == 0 && seen[num/2]) || seen[num*2] {
            return true
        }
        seen[num] = true
    }

    return false
}

Luhn's Algorithm

The second task involves implementing Luhn's Algorithm to validate a string of digits, ignoring non-digit characters. The last digit is considered separately as the payload.

Task Description

You are given a string str containing digits (and possibly other characters which can be ignored). The last digit is considered as the payload and handled separately.

  1. Counting from the right, double the value of the first, third, etc., of the remaining digits.
  2. For each value now greater than 9, sum its digits.
  3. The correct check digit is the one that, when added to the sum of all values, brings the total modulo 10 to zero.

Return true if the payload equals the correct check digit; otherwise, return false.

Examples:

Input: "17893729974"
Output: true

Payload is 4.

Digits from the right:

7 * 2 = 14, sum = 5
9 = 9
9 * 2 = 18, sum = 9
2 = 2
7 * 2 = 14, sum = 5
3 = 3
9 * 2 = 18, sum = 9
8 = 8
7 * 2 = 14, sum = 5
1 = 1

Sum of all values = 56, so 4 must be added to bring the total mod 10 to zero. The payload is indeed 4.
Input: "4137 8947 1175 5904"
Output: true
Input: "4137 8974 1175 5904"
Output: false

Solution

Perl Implementation
The Perl implementation processes the input string to ignore non-digit characters, then applies Luhn's algorithm to validate the number.

sub luhn_check {
    my ($str) = @_;
    $str =~ s/[^0-9]//g;

    my $payload = substr($str, -1);
    my $sum = 0;
    my $length = length($str);

    for (my $i = 0; $i < $length - 1; $i++) {
        my $digit = substr($str, $length - 2 - $i, 1);
        if ($i % 2 == 0) {
            $digit *= 2;
            $digit -= 9 if $digit > 9;
        }
        $sum += $digit;
    }

    my $check_digit = (10 - ($sum % 10)) % 10;

    return $payload == $check_digit ? 1 : 0;
}

Go Implementation
The Go version implements the same logic, utilizing the unicode package to filter out non-digit characters.

func luhnCheck(str string) bool {
    sum := 0
    payload := 0
    digits := []int{}

    for _, char := range str {
        if unicode.IsDigit(char) {
            digit := int(char - '0')
            digits = append(digits, digit)
        }
    }

    if len(digits) == 0 {
        return false
    }

    payload = digits[len(digits)-1]

    for i := 0; i < len(digits)-1; i++ {
        digit := digits[i]
        if (len(digits)-2-i)%2 == 0 {
            digit *= 2
            if digit > 9 {
                digit -= 9
            }
        }
        sum += digit
    }

    checkDigit := (10 - (sum % 10)) % 10

    return payload == checkDigit
}

Conclusion

In this article, we explored two interesting programming challenges: finding double existence in an array and implementing Luhn's Algorithm for validation. These tasks highlight how different programming languages can tackle similar problems with their own unique approaches. I hope these examples inspire you to delve deeper into both Perl and Go!

You can find the complete code, including tests, on GitHub.

perlfunc - update each documentation with foreach examples

Also mention multiple-value foreach as a new alternative, and fix a hash dereference in a previous example.

Maintaining Perl 5 Core (Dave Mitchell): September 2024

Perl Foundation News

Published by alh on Wednesday 09 October 2024 07:35


Dave writes:

This is my monthly report on work done during September 2024 covered by my TPF perl core maintenance grant.

I spent most of last month continuing to do various bits of code refactoring and test-adding on Extutils::ParseXS, as a precursor to adding reference-counted stack (PERL_RC_STACK) abilities to XS.

SUMMARY:

  • 5:02 process p5p mailbox
  • 2:06 reduce smoke failures
  • 54:15 refactor Extutils::ParseXS

Total: * 61:23 TOTAL (HH::MM)

Why The Perl and Raku Foundation Supports The Open Source Pledge

Perl Foundation News

Published by Stuart J Mackintosh on Tuesday 08 October 2024 11:00

The Open Source Pledge

We at The Perl and Raku Foundation are supporting the Open Source Pledge initiative.

The Open Source Pledge consists of companies with a shared commitment to paying the maintainers of the open source software they consume, therefore aims to help address sustainability challenges facing the Open Source community.

The Sustainability Challenge in OSS

Open source software is the backbone of much of today’s technology, but it relies heavily on the unpaid work of maintainers. As these volunteers struggle with burnout, turnover among OSS maintainers is high. Without the necessary support, key projects face the risk of disruption, which has far-reaching implications for the broader tech ecosystem. We have already seen the devastating effects of underfunded projects.

The Perl and Raku Foundation's Role in OSS

The Perl and Raku Foundation goal is to build a strong, healthy and sustainable language ecosystem and community. We also understand the importance of sustained funding for OSS projects. Through our community and core maintenance grants, we will provide support to developers who maintain essential infrastructure. These few dedicated individuals keep key components running, which are relied upon by both commercial systems and the broader internet.

This funding is necessary not only for technical upkeep but also for the non-technical aspects of managing open source communities. Without this support, the risk of losing essential contributors and the valuable work they do is too great.

This model of sustainability funding goes beyond just code contributions and aligns with the goals of the Open Source Pledge. It shows how financial support can be leveraged to maintain not just software, but entire developer ecosystems. This reinforces the importance of initiatives like the Open Source Pledge in supporting the broader open source ecosystem.

The Case for Joining the Pledge

The Open Source Pledge sets a new standard for how companies can contribute to OSS sustainability. By joining, companies commit to paying at least $2,000 per year for each developer on staff, with transparency through an annual report that details their payments.

We encourage other organizations to join us in supporting the Open Source Pledge, and using this as a method to set the value of your donations. By doing so, you’ll help ensure that the Perl and Raku ecosystem as well as the wider Open Source efforts remain healthy and sustainable, and that developers are recognized for the critical work they do. For more information about the Open Source Pledge and how to participate, please visit https://osspledge.com/

This is a welcome step in the right direction. "The Open Source Pledge is a crucial step towards ensuring the long-term sustainability of the open source ecosystem and by participating in this pledge, businesses can play a role in fostering innovation and maintaining the digital infrastructure we all rely on." Stuart Mackintosh, President of The Perl and Raku Foundation.

You can support The Perl and Raku Foundation directly using the method described by the Open Source Pledge, or any other amount that you can afford, details on our donations page here.

(dxvi) 13 great CPAN modules released last week

Niceperl

Published by Unknown on Sunday 06 October 2024 18:55

Updates for great CPAN modules released last week. A module is considered great if its favorites count is greater or equal than 12.

  1. App::perlbrew - Manage perl installations in your $HOME
    • Version: 1.00 on 2024-10-04, with 178 votes
    • Previous CPAN version: 0.99 was 27 days before
    • Author: GUGOD
  2. Catmandu - a data toolkit
    • Version: 1.2022 on 2024-09-29, with 23 votes
    • Previous CPAN version: 1.2021 was 10 months, 23 days before
    • Author: HOCHSTEN
  3. Convert::Binary::C - Binary Data Conversion using C Types
    • Version: 0.85 on 2024-10-01, with 14 votes
    • Previous CPAN version: 0.84 was 3 years, 10 months, 8 days before
    • Author: MHX
  4. Data::DPath - DPath is not XPath!
    • Version: 0.60 on 2024-09-29, with 13 votes
    • Previous CPAN version: 0.59 was 1 year, 2 months, 5 days before
    • Author: SCHWIGON
  5. DateTime::Format::Flexible - DateTime::Format::Flexible - Flexibly parse strings and turn them into DateTime objects.
    • Version: 0.35 on 2024-10-06, with 14 votes
    • Previous CPAN version: 0.34 was 3 years, 2 months, 30 days before
    • Author: THINC
  6. HTTP::BrowserDetect - Determine Web browser, version, and platform from an HTTP user agent string
    • Version: 3.41 on 2024-10-02, with 23 votes
    • Previous CPAN version: 3.40 was 11 months, 14 days before
    • Author: OALDERS
  7. meta - meta-programming API
    • Version: 0.010 on 2024-10-01, with 13 votes
    • Previous CPAN version: 0.009 was 18 days before
    • Author: PEVANS
  8. Modern::Perl - enable all of the features of Modern Perl with one import
    • Version: 1.20241001 on 2024-10-01, with 51 votes
    • Previous CPAN version: 1.20240120 was 8 months, 12 days before
    • Author: CHROMATIC
  9. PDL - Perl Data Language
    • Version: 2.093 on 2024-09-29, with 58 votes
    • Previous CPAN version: 2.019 was 6 years, 4 months, 24 days before
    • Author: ETJ
  10. PerlPowerTools - BSD utilities written in pure Perl
    • Version: 1.047 on 2024-09-30, with 39 votes
    • Previous CPAN version: 1.046 was 2 months, 19 days before
    • Author: BRIANDFOY
  11. SPVM - The SPVM Language
    • Version: 0.990016 on 2024-10-04, with 33 votes
    • Previous CPAN version: 0.990012 was 8 days before
    • Author: KIMOTO
  12. Syntax::Construct - Explicitly state which non-feature constructs are used in the code.
    • Version: 1.038 on 2024-10-01, with 13 votes
    • Previous CPAN version: 1.037 was 3 months, 11 days before
    • Author: CHOROBA
  13. Type::Tiny - tiny, yet Moo(se)-compatible type constraint
    • Version: 2.006000 on 2024-09-29, with 140 votes
    • Previous CPAN version: 2.004000 was 1 year, 5 months, 24 days before
    • Author: TOBYINK

(dxci) metacpan weekly report - Parallel::ForkManager

Niceperl

Published by Unknown on Sunday 06 October 2024 18:53

This is the weekly favourites list of CPAN distributions. Votes count: 59

Week's winner (+3): Parallel::ForkManager 

Build date: 2024/10/06 16:52:41 GMT


Clicked for first time:


Increasing its reputation:

(dcxix) stackoverflow perl report

Niceperl

Published by Unknown on Sunday 06 October 2024 18:52

The examples used here are from the weekly challenge problem statement and demonstrate the working solution.

Part 1: Third Maximum

You are given an array of integers, @ints. Write a script to find the third distinct maximum in the given array. If a third maximum doesn’t exist then return the maximum number.

The majority of the work can be done in a couple of lines. We need only sort the distinct integers in the list and then return either the third largest number or, if none exists, the largest.

sort and return the third largest (or just the largest) 1 ⟩≡


sub third_maximum{
my %h;
do{ $h{$_} = undef } for @_;
my @sorted = sort {$b <=> $a} keys %h;
return $sorted[2] if @sorted >= 3;
return $sorted[0];
}

Fragment referenced in 2.

The rest of the code just tests this function.

"ch-1.pl" 2


preamble 3
sort and return the third largest (or just the largest) 1
main 4

preamble 3 ⟩≡


use v5.40;

Fragment referenced in 2, 9.

main 4 ⟩≡


MAIN:{
say third_maximum 5, 6, 4, 1;
say third_maximum 4, 5;
say third_maximum 1, 2, 2, 3;
}

Fragment referenced in 2.

Sample Run
$ perl perl/ch-1.pl 
4 
5 
1
    

Part 2: Jumbled Letters

Your task is to write a program that takes English text as its input and outputs a jumbled version

The rules for jumbling are given as follows:

  1. The first and last letter of every word must stay the same.
  2. The remaining letters in the word are scrambled in a random order (if that happens to be the original order, that is OK).
  3. Whitespace, punctuation, and capitalization must stay the same.
  4. The order of words does not change, only the letters inside the word.

Looking closer at these rules the main thing we need to concern ourselves with is jumbling the letters with the exception of the first and last. The use of map will ensure the words are processed in order. To make sure the first/last letters are unchanged also depends on detecting punctuation.

Punctuation is determined by a regex. We’ll keep track of the locations so we can add them back later, after jumbling.

strip punctuation 5 ⟩≡


my $stripped = [];
my $punctuation = [];
do{
$punctuation->[$_] = $w->[$_] if $w->[$_] =~ m/[[:punct:]]/;
push @{$stripped}, $w->[$_] if $w->[$_] !~ m/[[:punct:]]/;
} for 0 .. @{$w} - 1;

Fragment referenced in 8.

Defines: $punctuation 7, $stripped 6, 7.

Uses: $w 8.

Now that we have the punctuation accounted for let’s do the jumble. We’ll do this by generating permutations and randomly select one.

permutate the letters 6 ⟩≡


my $p = Algorithm::Permute->new(
[@{$stripped}[1 .. @{$stripped} - 2]]
);
my @p;
if(@{$stripped} > 2){
my @r = $p->next();
{
push @p, [@r];
@r = $p->next();
redo if @r;
}
$stripped = [$stripped->[0] ,
@{$p[rand @p]} ,
$stripped->[@{$stripped} - 1]];
}
$stripped = join q//, @{$stripped};

Fragment referenced in 8.

Uses: $stripped 5.

Finally, add the punctuation back in.

add punctuation back 7 ⟩≡


do{
substr $stripped, $_, 0, $punctuation->[$_]
if $punctuation->[$_];
} for 0 .. @{$punctuation} - 1;
$stripped . q/ /;

Fragment referenced in 8.

Uses: $punctuation 5, $stripped 5.

jumble the list of words 8 ⟩≡


sub jumble{
return map {
my $w = [split //, $_];
strip punctuation 5
permutate the letters 6
add punctuation back 7
} @_;
}

Fragment referenced in 9.

Defines: $w 5.

The rest of the code drives some tests.

"ch-2.pl" 9


preamble 3
use Algorithm::Permute;
jumble the list of words 8
main 10

main 10 ⟩≡


MAIN:{
say q/in the ASCII range match all non-controls./;
say jumble qw/in the ASCII range match all non-controls./;
say q//;
say q/This handy module makes performing permutation.../;
say jumble qw/This handy module makes performing permutation.../;
}

Fragment referenced in 9.

Sample Run
$ perl perl/ch-2.pl 
in the ASCII range match all non-controls. 
in the AISCI range macth all non-rloncots. 
 
This handy module makes performing permutation... 
Tihs handy mloude mkaes prifnremog prtaoimetun...
    

References

The Weekly Challenge 289
Generated Code


Paul writes:

With the 5.40 release well out of the way, and freed from my PSC commitments, I managed to find a bit more time this month to actually write some useful code.

Hours:

  • 2 = Improvements to op_dump() for custom operators

    • https://github.com/Perl/perl5/pull/22572
  • 1 = Improvements to op_dump() on existing UNOP_AUX operators

    • https://github.com/Perl/perl5/pull/22573
  • 11 = Additions to meta module: various "list"-type methods, set_prototype + set_subname on metasubroutines, add_named_sub helper method, is_class + is_method

    • https://metacpan.org/release/PEVANS/meta-0.009/source/Changes#L3
    • https://metacpan.org/release/PEVANS/meta-0.009/source/Changes#L12

Total: 14 hours

Thank you for the fundraising at YAPC::Hiroshima in Japan

Perl Foundation News

Published by Makoto Nozaki on Friday 04 October 2024 08:00

The Japan Perl Association made a generous donation to The Perl and Raku Foundation following their fundraising activity at YAPC::Hiroshima (article link). Here is a thank you message from Olaf Adler:

Thank you from TPF!

Japanese translation below:

日本語抄訳

こんにちは。Olaf Alderと申します。The Perl Foundationで後援者様向け広報の担当をしています。今日は日本のPerlコミュニティの皆様に感謝の意を表したく、ご連絡差し上げました。

Japan Perl AssociationとYAPC::Japanの皆様には、長年にわたるご支援を誠に「ありがとう」ございます。特に先日のYAPC::Hiroshimaの大盛況をお祝い申し上げます。写真で見た酒樽募金箱は印象的で、今後、私は日本酒を飲むたびにこのイベントを思い出すでしょう。

YAPCの継続的な成功は素晴らしいです。日本チームの秘訣を世界に伝えてほしいと願っています。私たちも多くを学びたいと思います。

Japan Perl AssociationはThe Perl Foundationの大切なパートナーです。今後とも協力し、Perlの発展に努めましょう。YAPC::Hakodateの盛会をお祈りしています。ありがとうございます!

Debugging Perl Scripts: Tools and Techniques

Perl on Medium

Published by Mayur Koshti on Wednesday 02 October 2024 16:07

Perl debugging tools and techniques to make debugging more manageable.

(dxv) 5 great CPAN modules released last week

Niceperl

Published by Unknown on Saturday 28 September 2024 22:40

Updates for great CPAN modules released last week. A module is considered great if its favorites count is greater or equal than 12.

  1. App::cpm - a fast CPAN module installer
    • Version: 0.997018 on 2024-09-23, with 72 votes
    • Previous CPAN version: 0.997017 was 4 months, 25 days before
    • Author: SKAJI
  2. Mozilla::CA - Mozilla's CA cert bundle in PEM format
    • Version: 20240924 on 2024-09-24, with 19 votes
    • Previous CPAN version: 20240730 was 1 month, 25 days before
    • Author: LWP
  3. Plack::Middleware::Session - Middleware for session management
    • Version: 0.34 on 2024-09-23, with 16 votes
    • Previous CPAN version: 0.33 was 5 years, 6 months, 14 days before
    • Author: MIYAGAWA
  4. SPVM - The SPVM Language
    • Version: 0.990012 on 2024-09-26, with 33 votes
    • Previous CPAN version: 0.990010 was 8 days before
    • Author: KIMOTO
  5. XML::Hash::XS - Simple and fast hash to XML and XML to hash conversion written in C
    • Version: 0.57 on 2024-09-27, with 12 votes
    • Previous CPAN version: 0.56 was 3 years, 7 months, 14 days before
    • Author: YOREEK

my problems with CP2077 (and lots of RPGs)

rjbs forgot what he was saying

Published by Ricardo Signes on Saturday 28 September 2024 12:00

When Cyberpunk 2077 was announced, I was really excited. The teaser for it looked exactly like the Cyberpunk 2020 RPG that I’d like so much when I was a kid. When it came out, I tried it and it was a mess. Later, I heard they worked out lots of the problems, and I went back and I’ve been playing it. It still looks just about perfect, and gets lots of things right. It feels like a really good adaptation of Cyberpunk 2020. There are a lot of bugs and interface issues, still, but I don’t want to write about those, because it’s boring.

My problem is that the world of 2077 seems to have changed zero since 2013. From 1990 to 2013, in twenty three years: the USA collapses, space colonization (of the moon and Mars) begins in earnest, cybernetic prosthesis and mind uploading become practical, European nations collapse and reform, and powerful artificial general intelligence is developed. It’s an incredible amount of change to the world for twenty three years. Think back to 2001. How much has the world changed? Some, for sure, but really nothing like Cyberpunk proposes. That’s okay, because Cyberpunk is a game that proposes a world where everything is in a state of constant upheaval. But sixty five years later, the world hasn’t changed any further.

My problem is that CP2077 keeps reminding me of something that often bugged me about RPGs in the ’90s. Back then, I had a mailing list with some friends who were into RPGs. It was called “RPG Theory”, and that’s what we talked about. Here’s a (lightly edited) section of a post I made in August 2000, with the subject “Metaplot, Setting, Freedom, and Flavor”:


A role-playing game (RPG) is an interactive story-game created by a Game Designer, revolving mostly (although not exclusively) around the actions of Player Characters (PCs) largely told and entirely adjudicated by the Game Master (GM).

The game can be roughly defined by its theme, setting, and rules.

The game’s theme is composed of its mood, tone, and possibly an overall moral or message. The necessity of a particular mood to a game is hard to define. While slight variation is clearly possible (e.g. Vampire games centered chiefly around Humanitas or Jyhad), it may be that vast changes are not. (A Vampire game centered around fighting robots from Mars, or in the style of Paranoia.) I leave this question to the philosophers.

The games’s setting is the world in which the game takes place. This world exists in equilibrium or stasis. It is clearly not frozen in one moment, but it is frozen in one period. One can look at Casablanca and see a setting that is active, but also frozen. From the beginning to the end of the description (that is, the movie itself), the setting does not change. Only the characters change and take action.

Setting is the perogative of the Game Designer. They write the game’s chief book or books, which contain as basic description of rules and setting.

The perogative of the Player Character, chiefly and above all else, is action. Actions are easy to understand. When a PC speaks to another PC, shoots an NPC, or detonates a nucelar device, these are actions. They are undertaken by the PC as in-character (IC) tasks, generally with the implicit permission of the Game Master, which can use IC means to stop them, but will rarely rule out-of-hand that an attempt is impossible.

The perogative of the Game Master, chiefly and above all else, is motion. Motion is action taken by the setting. While the setting, as initially described, is static, during the course of the game it acts. This motion can be subtle: gangs working for the city’s mayor begin to muscle in on the PCs’ operation, which had in the Prelude (pre-game ‘time’) existed in equilibrium. It can also be drastic: all the women in America begin to grow wings. Through motion, the GM punctuates the equilibrium of the setting, communicates the theme, and forces the PCs to take action.

That is a campaign. (Or Chronicle, or Session, whatever.)

Metaplot is the superimposition of the Game Designer’s campaign onto the GM’s campaign. (The Game Designer, in his off time, presumably is able to act also as a GM.) The Game Designer’s motion must be accounted for by the Game Master, and this reduces his ability to communicate theme and act effectively. Or, at least, this is how many GMs perceive the problem. We could call the metaplot “metamotion.” (It is run by the Designer as ‘metaGM’ and stars ‘metacharacters.’)

The Golden Rule, “the GM can do whatever they want”, gives GMs the option to ignore any part of the Game Designer’s ideas. Generally this applies to setting, but it can be extended to rules, theme, and (of course) metaplot.

On the other hand, the Game Designer knows that GMs are unlikely to abandon “canon” rules. So, the Game Designer insidiously (or blithely) incorporates new metaplot into new rules, making it impossible for one to exist without the other. Or, only slightly less insidiously, they release books of metaplot which also contain useful or required information that can be discounted, which merely means that the GM will pay for material that they do want, as well as material that they do not.


The Cyberpunk RPG had its own metaplot. Books came out once in a while telling you what was new in the world. Night City is seized by the Metal Wars. Elziabeth Kress becomes President of the United States. The Fourth Corporate Wars happen. These books were generally of the “less insidious” type above: the book would tell you about how Arasaka and Militech were warring over an African land grab, and also introduce new weapons and cyberware being used there. You could use that story as a basis for your game, or you could ignore it and give the players access to the cool new tech just for fun.

Of course, as the years go by, more and more of this metaplot builds up. New books are released that build on the story of the last ten books. It’s harder and harder to carve out your game’s Night City from the currently canonical one. Cyberpunk was hardly the worst offender (if you consider this an offense) in this area. I wrote my post about White Wolf’s World of Darkness, which started off by describing the game world as a moment in time, and ended up releasing an enormous list of books detailing monumental in-game events that crowded out the Game Master’s own ideas.

Anyway, Cyberpunk 2077 feels enormously encumbered by this problem. Johnny Silverhand has been part of the Cyberpunk story since the original Cyberpunk RPG (set in 2013). His activities help define the setting, not just in the setting’s past, but in its present and future. His actions are so significant as to constrain the motion of the game.

This just becomes bizarre when we’re not thinking about the seven years from CP 2013 to CP 2020, but the 57 years from CP 2020 to CP 2077. Johnny blows up Arasaka tower in 2022, and then vanishes for fifty years. When he shows up again, nothing has changed. The world of 2077 is, I would say, literally indistinguishable from that of 2022. It’s not because Johnny isn’t there to do stuff, but because it’s not an option to really decontextualize Johnny by having the setting change out from under him.

Johnny complains about some fan of his from fifty years ago who’s living in the past, but actually nothing has changed since then. Johnny isn’t a creature of the past, he’s just as relevant in 2077 as he was in 2022. This world of constant upheaval and instability has become incredibly reliable. In sixty years, nothing really changed. The protagonist can’t really change anything, either. They’re just there to experience the show.

I wish the game had been set in 2022. They could’ve just let us play as Johnny Silverhand, carrying out the raid on Arasaka. But this would’ve given us agency over a character whose actions belong to the game designer, or maybe one of their friends in the canonical campaign of the game. They couldn’t let us have that agency, so they gave us the lesser agency of V, who lets us see that Johnny’s actions had no consequence, and neither will ours.

All of this is why I basically always throw away the setting that comes with an RPG. Anything that limits my ability to create a dynamic world of my own is antithetical to my idea of being a game master. The way that CP 2077 reflects a world defined by the game designer’s favorite NPCs and their millieu just makes me sad.

List of new CPAN distributions – Aug 2024

Perlancar

Published by perlancar on Friday 27 September 2024 04:29

dist author abstract date
Acme-CPANModules-MultipleDispatch PERLANCAR List of modules to do smart matching 2024-08-18T00:05:41
Acme-CPANModules-UnixCommandVariants PERLANCAR List of various CLIs that are some variants of traditional Unix commands 2024-08-26T09:48:48
Acme-Free-API-ChuckNorris OODLER Perl API client for the Chuck Norris Quote API service, https://api.chucknorris.io. 2024-08-29T18:39:41
Acme-Free-API-Stonks OODLER Perl API client for the, top 50 stocks discussed on le'Reddit subeddit – r/Wallstreetbets, https://tradestie.com/apps/reddit/api/. 2024-08-30T16:21:46
Acme-Free-API-Ye OODLER Perl API client for the Kanye Rest Quote API service, https://kanye.rest/. 2024-08-28T16:39:49
App-BookmarkFeed SCHROEDER Create a RSS feed from Markdown files 2024-08-05T16:33:07
App-optex-mask UTASHIRO optex data masking module 2024-08-16T10:14:16
App-prefixcat PERLANCAR Like Unix `cat` but by default prefix each line with filename 2024-08-09T12:33:04
Ascii-Text LNATION module for generating ASCII text in various fonts and styles 2024-08-29T10:49:18
Autoconf-Template BIGFOOT autoconfiscation help scripts 2024-08-06T09:26:35
Bio-EnsEMBL ABECKER Bio::EnsEMBL – Ensembl Core API 2024-08-29T16:32:54
Business-ID-VehiclePlate PERLANCAR Parse Indonesian vehicle plate number 2024-08-07T00:05:46
Catalyst-Plugin-Profile-DBI-Log BIGPRESH Capture queries executed during a Catalyst route with DBI::Log 2024-08-29T23:41:08
Circle-Block CHENGYU the block module for Circle::Chain SDK 2024-08-29T06:33:17
Circle-Chain CHENGYU The great new Circle::Chain! 2024-08-29T02:33:58
Circle-Common CHENGYU the common module for Circle::Chain SDK 2024-08-29T06:31:49
Circle-User CHENGYU the user module for Circle::Chain SDK 2024-08-29T06:36:47
Circle-Wallet CHENGYU the circle chain SDK in PERL 2024-08-29T06:36:58
DBIx-Squirrel CPANIC A module for working with databases 2024-08-08T20:01:38
Dancer2-Session-DBI EPISODEIV DBI based session engine for Dancer 2024-08-29T13:55:42
DateTime-Locale-FromCLDR JDEGUEST DateTime Localised Data from Unicode CLDR 2024-08-01T22:59:44
Dist-Build-XS-Alien LEONT Dist::Build extension to use Alien modules. 2024-08-31T19:19:30
File-ShareDir-Tiny LEONT Locate per-dist and per-module shared files 2024-08-25T13:07:29
Github-ReleaseFetcher TEODESIAN Fetch either the latest or a particular named version of a file in a release from github 2024-08-13T22:09:19
IO-SocketAlarm NERDVANA Perform asynchronous actions when a socket changes status 2024-08-27T06:08:13
IPC-MicroSocket PEVANS minimal request/response or pub/sub mechanism 2024-08-05T13:49:53
JIRA-REST-Lite SHINGO Lightweight wrapper around Jira's REST API 2024-08-16T01:20:46
Langertha GETTY The clan of fierce vikings with axe and shield to AId your rAId 2024-08-03T20:56:05
Locale-Unicode-Data JDEGUEST Unicode CLDR SQL Data 2024-08-01T22:43:58
Map-Tube-Rome GDT Interface to the Rome tube map 2024-08-27T16:01:05
MetaCPAN-Pod-HTML HAARG Format Pod as HTML for MetaCPAN 2024-08-26T14:55:52
MooseX-JSONSchema GETTY Adding JSON Schema capabilities to your Moose class 2024-08-03T20:36:33
Net-OpenSSH-More TEODESIAN Net::OpenSSH submodule with many useful features 2024-08-09T00:03:26
Object-Pad-Operator-Of PEVANS access fields of other instances 2024-08-22T11:30:12
OpenFeature-SDK CATOUC OpenFeature SDK for Perl 2024-08-17T19:40:04
Plack-App-Catmandu-OAI NJFRANCK drop in replacement for Dancer::Plugin::Catmandu::OAI 2024-08-23T07:58:26
Protocol-Sys-Virt-Devel EHUELS Development helper for Protocol::Sys::Virt and its dependants 2024-08-31T20:48:14
Protocol-Sys-Virt EHUELS Transport independent implementation of the remote LibVirt protocol 2024-08-31T21:36:13
Regex-Common ARFREITAS Provide commonly requested regular expressions 2024-08-12T22:48:17
Rope-Cmd LNATION Command Line Applications via Rope 2024-08-30T20:00:03
RxPerl-Extras KARJALA extra operators for RxPerl 2024-08-06T10:18:15
Sah-SchemaBundle-DNS PERLANCAR Schemas related to DNS 2024-08-04T00:05:19
Sah-SchemaBundle-Data-Sah PERLANCAR Sah schemas related to Data::Sah 2024-08-11T00:06:03
Sah-SchemaBundle-DataSizeSpeed PERLANCAR Sah schemas related to data sizes & speeds (filesize, transfer speed, etc) 2024-08-02T21:50:19
SlapbirdAPM-Agent-Dancer2 RAWLEYFOW Agent software for the Perl application performance monitor, Slapbird. slapbirdapm.com 2024-08-25T20:49:02
SlapbirdAPM-Agent-Mojo RAWLEYFOW Agent software for the Perl application performance monitor, Slapbird. slapbirdapm.com 2024-08-09T21:00:04
SlapbirdAPM-Agent-Plack RAWLEYFOW A Plack agent software for the Perl application performance monitor, Slapbird. slapbirdapm.com 2024-08-18T02:37:49
Syntax-Keyword-Assert KFLY assert keyword for Perl 2024-08-14T13:53:23
Task-MemManager CHRISARG A memory allocator for low level code in Perl. 2024-08-25T23:42:18
Term-ANSI-Sprintf LNATION sprintf with ANSI colors 2024-08-25T09:46:37
Tk-PodViewer HANJE Simple ROText based pod viewer. 2024-08-20T20:06:36
kura KFLY Store constraints for Data::Checks, Type::Tiny, Moose and more. 2024-08-18T13:31:06

Stats

Number of new CPAN distributions this period: 52

Number of authors releasing new CPAN distributions this period: 29

Authors by number of new CPAN distributions this period:

No Author Distributions
1 PERLANCAR 7
2 CHENGYU 5
3 RAWLEYFOW 3
4 LNATION 3
5 OODLER 3
6 LEONT 2
7 TEODESIAN 2
8 JDEGUEST 2
9 GETTY 2
10 KFLY 2
11 PEVANS 2
12 EHUELS 2
13 EPISODEIV 1
14 SCHROEDER 1
15 NERDVANA 1
16 BIGFOOT 1
17 CHRISARG 1
18 ABECKER 1
19 SHINGO 1
20 KARJALA 1
21 BIGPRESH 1
22 NJFRANCK 1
23 ARFREITAS 1
24 HAARG 1
25 HANJE 1
26 GDT 1
27 UTASHIRO 1
28 CPANIC 1
29 CATOUC 1

List of new CPAN distributions – Jul 2024

Perlancar

Published by perlancar on Friday 27 September 2024 04:28

dist author abstract date
Acme-CPANModules-ModifiedHashes PERLANCAR List of modules that provide hashes with modified behaviors 2024-07-13T02:14:33
App-GeometryUtils PERLANCAR Utilities related to geometry 2024-07-07T00:05:12
App-LastStats DAVECROSS A module to fetch and display Last.fm statistics 2024-07-28T17:34:18
App-PerlGzipScript SKAJI Gzip perl scripts to reduce their file size 2024-07-20T12:49:29
App-YtDlpUtils PERLANCAR Utilities (mostly wrappers) related to yt-dlp 2024-07-10T02:59:34
Astro-MoonPhase-Simple BLIAKO Calculate the phase of the Moon on a given time without too much blah blah 2024-07-14T14:14:36
Audio-Cuefile-Libcue GREGK Perl interface to the libcue cuesheet reading library 2024-07-19T19:43:23
Bencher-ScenarioBundle-SmartMatch PERLANCAR Scenarios to benchmark switch & smartmatch in Perl 2024-07-03T09:45:27
CVSS GDT CVSS (Common Vulnerability Scoring System) command line interface 2024-07-30T22:11:37
Catmandu-Store-OpenSearch NJFRANCK A searchable store backed by Opensearch 2024-07-03T07:23:38
Consumer-NonBlock EXODIST Send data between processes without blocking. 2024-07-02T19:53:48
Dancer2-Plugin-NYTProf GEEKRUTH NYTProf, in your Dancer2 application! 2024-07-02T13:03:01
Data-LnArray-XS LNATION Arrays 2024-07-12T09:58:12
Data-Random-Person SKIM Generate random person. 2024-07-05T00:10:57
Exercises-API NOBUNAGA API Ninja's Exercises API 2024-07-02T19:49:44
Extender DOMERO Dynamically enhance Perl objects with additional methods from other modules or custom subroutines 2024-07-17T10:06:50
Kanboard-API BARBARITO A Perl interface to the Kanboard API 2024-07-28T23:46:12
KelpX-Controller BRTASTIC Base custom controller for Kelp 2024-07-08T14:43:24
MIDI-RtMidi-ScorePlayer GENE Play a MIDI score in real-time 2024-07-10T23:51:51
Math-GSL-Alien HAKONH Easy installation of the GSL shared library 2024-07-17T09:42:10
Number-Iterator-XS LNATION iterate numbers faster 2024-07-26T03:56:33
OpenMP OODLER Metapackage for using OpenMP in Perl 2024-07-19T21:12:29
Perl-PrereqScanner-Scanner-DistBuild LEONT scan for Dist::Build dependencies 2024-07-12T12:03:35
Plack-App-Catmandu-SRU NJFRANCK drop in replacement for Dancer::Plugin::Catmandu::SRU 2024-07-30T09:27:07
SPVM-Resource-Eigen KIMOTO Resource for C++ Eigen library 2024-07-16T23:56:40
Sah-SchemaBundle-Country PERLANCAR Various Sah schemas related to country codes/names 2024-07-14T00:05:31
Sah-SchemaBundle-Currency PERLANCAR Various Sah currency schemas 2024-07-21T00:06:11
Sah-SchemaBundle-DBI PERLANCAR Schemas related to DBI 2024-07-28T00:06:12
Shannon-Entropy-XS LNATION Calculate the Shannon entropy H of a given input string faster. 2024-07-18T19:43:55
Slack-BlockKit RJBS a toolkit for building BlockKit blocks for Slack 2024-07-04T01:51:26
String-Mask-XS LNATION mask sensitive data faster 2024-07-03T21:44:29
Syntax-Operator-Is PEVANS match operator using Data::Checks constraints 2024-07-08T14:59:03
TableData-Business-ID-Kemenkes-RDA PERLANCAR Indonesian RDA (AKG, Angka Kecukupan Gizi) 2024-07-02T03:05:09
Text-Schmutz RRWO You̇r screen is quiṭe dirty, please cleȧn it. 2024-07-11T22:41:24
Text-Template-Tiny JV Variable substituting template processor 2024-07-05T11:10:37
Tk-Terminal HANJE Running system commands in a Tk::Text widget. 2024-07-03T09:24:21
Tradestie-WSBetsAPI NOBUNAGA Tradestie's Wallstreet Bets API 2024-07-01T19:57:16
WebService-GrowthBook DERIV 2024-07-02T11:17:20
Whelk BRTASTIC A friendly API framework based on Kelp 2024-07-03T13:59:32
Win32-Console-DotNet BRICKPOOL Win32 Console .NET interface 2024-07-29T07:05:25
Win32API-RecentFiles CORION recently accessed file API functions on Windows 2024-07-29T18:16:24

Stats

Number of new CPAN distributions this period: 41

Number of authors releasing new CPAN distributions this period: 28

Authors by number of new CPAN distributions this period:

No Author Distributions
1 PERLANCAR 8
2 LNATION 4
3 NJFRANCK 2
4 BRTASTIC 2
5 NOBUNAGA 2
6 OODLER 1
7 GENE 1
8 RJBS 1
9 SKAJI 1
10 DAVECROSS 1
11 GREGK 1
12 LEONT 1
13 GEEKRUTH 1
14 BARBARITO 1
15 EXODIST 1
16 HAKONH 1
17 GDT 1
18 DOMERO 1
19 BRICKPOOL 1
20 HANJE 1
21 SKIM 1
22 RRWO 1
23 JV 1
24 CORION 1
25 DERIV 1
26 BLIAKO 1
27 PEVANS 1
28 KIMOTO 1

Perl: The Language of Text Manipulation and Beyond

Perl on Medium

Published by Mwenda Kelvin on Thursday 26 September 2024 21:01

Explore how Perl, the language of text manipulation, empowers developers with powerful features for scripting, automation, and robust data…

Dancing with Copilot Workspace

Perl Hacks

Published by Dave Cross on Sunday 22 September 2024 16:00

Over the last few months, I’ve been dabbling in using AI to generate or improve code. I have a subscription to GitHub Copilot and I’m finding it a really useful tool for increasing my productivity. Copilot comes in several different flavours, and I’ve been making particular use of a couple of them.

  • Copilot Autocomplete was the first Copilot tool that GitHub released. Once you’ve configured your editor to use it, the AI will read the file you’re working on and will monitor what you’re typing. When it thinks it knows what you’re doing and what comes next, it will display a suggestion for the next chunk of code and if you like what you see, you can just hit the tab key to accept it. I’ve been pleasantly surprised by how well it does. I’ve had cases where I’ve just typed the name of a method and it has autocompleted the code for me.
  • Copilot Chat was the next version to be released. This is a chat box that sits alongside your code where you can talk to the AI about what you’re doing and ask it for suggestions. This is great for taking on larger projects. I’ve found it particularly useful for working on front-end code. I can usually make CSS and Javascript do what I want, but asking Copilot for suggestions makes me an order of magnitude quicker.

Those two tools alone make me a more efficient programmer. And they’re well worth the $10 a month I pay for my Copilot subscription. But recently I was invited to the preview of Copilot Workspace. And that’s a whole new level. Copilot Workspace takes a GitHub issue as its input and returns a complete, multifile pull request that implements the required change. I’ve been playing with it for small tweaks, but I decided the time was right to do something more substantial. I planned to write an entire Dancer app by defining issues and asking Copilot to implement the code. Here’s what happened. You can follow along at the GitHub repo.

I decided I would start from the standard, automatically generated Dancer2 app. So I ran dancer2 gen -a Example and committed the output from that. It was then time for the first issue. I decided to start by adding (empty) routes for user registration and login. I opened the issue in the Copilot Workspace and asked the AI for some suggested code. It didn’t really understand the idea of empty routes – but the pull request seemed pretty good. I merged the PR and moved on to the next issue – to add basic registration and login screens. Again, the pull request did a little more than I asked for – adding a bit more registration and login logic – but the code was good.

As an aside, you’ll notice that the PRs are all correctly linked to the correct issues and contain substantial information about the changes. This is all generated by the AI.

For the next step, we needed a database table to store the users. I asked Copilot to use SQLite and it gave me what I wanted – once again, going above and beyond. For the first time, its overenthusiasm was slightly annoying, because it added some database code to store new users and I hadn’t told it that we would be using DBIx::Class. So that was the next issue and the next pull request. Note that the pull request even includes adding DBIx::Class to the requisites in Makefile.PL.

Time for some unit tests (ok, maybe the best time was a few PRs ago!). The issue description was simple – “Write unit tests for everything we have so far“. Maybe it was too simple – as this was the first time the AI seemed to struggle a bit. I was merging the PRs without really checking them and the PR introduced a lot of useful tests – but many of them failed. Part of the problem here is that (as far as I can see) Copilot Workspace has no way to run the code it produces – so it was guessing how well it was doing. It took a few iterations to get that right – it basically boiled down to the database schema not being loaded into the database before the tests were run. At times while we were working through these problems, I was reminded of someone (I think it was Simon Willison) describing an AI programming assistant as “an overconfident, overenthusiastic intern”. Luckily, unlike an intern, Copilot never gets annoyed with you telling it to try again and providing more and more information to help it get to the bottom of a problem.

After a while, we had a working test suite and were back on track.

So we were back at adding features to the application. I decided the next thing we needed was to display the logged-in user’s username and email address on the main page. That seemed simple enough and worked first time. About this time I was getting annoyed with the standard Dancer2 web page, so we removed most of that. Then I switched from Dancer’s default “simple” templating system to the Template Toolkit [issue / PR].

While we were tidying up the look and feel, we added login and logout buttons [issue / PR] and a register button on the logged out page [issue / PR]. This led to some more confusion for a while as logging out didn’t work. It turned out the AI had used outdated code to destroy the session and I had to get very specific before it would do the right thing [issue / PR].

We then added some more tests [issue / PR], displayed registration and login errors [issue / PR] and ensured we were storing the passwords in encrypted form (to be honest, I’m slightly disappointed that the AI didn’t do that by default) [issue / PR].

At this point (and I don’t know why I didn’t do it sooner), we replaced the UI with something using Bootstrap [issue / PR]. That led to a bit more tweaking of the buttons [issue / PR].

At this point, I had basically got to where I wanted to be. I had an app that didn’t do anything useful, but let you register, login and log out. And I’d done it all pretty quickly and without writing very much code.

Then I decided to push it too far.

The thing that I actually wanted to achieve at this point was to add social registration and login to the site. I created an issue – Allow users to register and login using a Google account – and Copilot gave me some code. But at this point, it’s not just about code. You also need to configure stuff at Google in order to get this working. And, while Copilot gave me some information about what I needed to do, I haven’t yet been able to get it working. This is a good example of the limitations of AI-powered programming. It’s great at generating code, but (so far, at least) not so good at keeping up to date with how to interface with external systems. Oh, and there’s the problem we saw earlier about it not actually running the tests.

So, how do I think the experiment went? I was impressed. There was a lot of code generated that was as good or better than I would have written myself. There are certainly the problems that I mentioned above, but this stuff is improving at such an incredible rate that I really can’t see those problems still existing in a year.

I’ve started using Copilot Workspace for a lot more of my projects. And I’m happy with the results I’ve got.

What about you? Have you used any version of Copilot to help with your coding? How successful has it been?

The post Dancing with Copilot Workspace appeared first on Perl Hacks.

Taking VelociPerl for a ride

Killing-It-with-PERL

Published on Saturday 21 September 2024 00:00

VelociPerl is a closed source fork of Perl that claims performance gains of 45% over the stock (“your dad’s Perl” in their parlance) based on some public benchmarks. I will not go into how they achieved this performance boost, or why they released it as closed source, or even “but why the heck did you release it as closed source?”, as you can follow the Reddit discussion. However, even a modest speed gain may be useful in some applications, so I decided to dive in a a little bit deeper.

Some of the benchmarks are numerical e.g. a linear system solver, generating random numbers but others are more relevant to garden variety Perl tasks, e.g. generating objects as blessed hashes. These tasks may appear in the context of some applications, so it is nice to know there are some benefits, but why not come up with a composite task and benchmark it? My usage of Perl involves random number generation, operations on tasks, creation of objects, string concatenation and function calling, so I figured there should be a way to combine all of them together and take VelociPerl for a ride.

Consider the following code that executes two benchmarks:

  • Generating a Hash (in which the keys are random strings and the values are obtained as a blessed reference to an anonymous scalar)
  • Accessing the said hash
use v5.38;
use Benchmark qw(timethis);    # for benchmarking

my $Length_of_accesstest = 1_000_000;
my $Length_of_gentest=100_000;
my $class = 'HashingAround';    
sub generate_random_string(@alphabet) {
    my $len = scalar @alphabet;
    my $length = int( rand(100) ) + 1;    # random length between 1 and 100
    return join '', @alphabet[ map { rand  $len } 1 .. $length ];
}

my %hash_of_seqs;

for ( 1 .. $Length_of_accesstest ) {
    my $key = generate_random_string(('A' .. 'Z'));
    my $val = bless \do { my $anon_scalar = $key }, $class;
    $hash_of_seqs{$key} = $val;
}

say "=" x 80;
say "\tTiming hash access using timethis";
timethis(
    20,
    sub {
        while ( my ( $seq_id, $seq ) = each %hash_of_seqs ) {
            ## worthless access to seq to force the sequence to be copied in memory
            my $sequence = $seq;
        }
    }
);

say "=" x 80;
say "\tTiming hash generation using timethis";
timethis(
    10,
    sub {
        my %hash_of_seqs;
        for ( 1 .. $Length_of_gentest ) {
    my $key = generate_random_string(('A' .. 'Z'));
    my $val = bless \do { my $anon_scalar = $key }, $class;
            $hash_of_seqs{$key} = $val;
        }
    }
);

To switch the Perl interpreter one simply changes the shebang line. In my oldish dual Xeon E5-2697 v4, I obtained the following results

  • Stock Perl : ```text (base) chrisarg@chrisarg-HP-Z840-Workstation:~/software-dev/velociperlHash$ ./testHash_speed.pl ================================================================================ Timing hash access using timethis timethis 20: 12 wallclock secs (11.61 usr + 0.00 sys = 11.61 CPU) @ 1.72/s (n=20) ================================================================================ Timing hash generation using timethis timethis 10: 12 wallclock secs (12.58 usr + 0.01 sys = 12.59 CPU) @ 0.79/s (n=10)

* **VelociPerl** :
```text
(base) chrisarg@chrisarg-HP-Z840-Workstation:~/software-dev/velociperlHash$ ./testHash_speed_vperl.pl 
================================================================================
	Timing hash access using timethis
timethis 20: 11 wallclock secs (11.04 usr +  0.00 sys = 11.04 CPU) @  1.81/s (n=20)
================================================================================
	Timing hash generation using timethis
timethis 10: 10 wallclock secs ( 9.80 usr +  0.01 sys =  9.81 CPU) @  1.02/s (n=10)

Walking the hash was not materially different between the two interpreters, but the more compute intense task that involved random numbers, string operation and blessing of objects was ~30% faster. This gain may or may not justify using a closed source version of Perl to you. But it is worth noting that one may be able to tweak the compilation of the Perl source (which appears to be a major source of the claimed gains) to generate faster executing Perl code. Perhaps an approach that one can try with an open sourced fork?