Python equivalent of the Perl ".." (range, or flip-flop) operator

Perl questions on StackOverflow

Published by Timur Shtatland on Wednesday 06 November 2024 17:55

What is the Python equivalent of the Perl ".." (range, or flip-flop) operator?

for ( qw( foo bar barbar baz bazbaz bletch ) ) { 
    print "$_\n" if /ar.a/ .. /az\w/;
}

Output:

barbar
baz
bazbaz

The Python workaround that I am aware of includes generator expression and indexing with the help of enumerate, but this seems cumbersome:

import re

lst = 'foo bar barbar baz bazbaz bletch'.split()
idx_from = list(i for i, el in enumerate(lst) if re.search(r'ar.a', el))[0]
idx_to   = list(i for i, el in enumerate(lst) if re.search(r'az\w', el))[0]

lst_subset = lst[ idx_from : (idx_to+1)]
print(lst_subset)
# ['barbar', 'baz', 'bazbaz']

Note:

I am looking for just one range. There is currently no need to have multiple ranges.

SWIG Perl interface yields undefined symbol

Perl questions on StackOverflow

Published by Mike Lempriere on Wednesday 06 November 2024 17:19

I have some C code that I'm trying to access from Perl. Just a few very simple calls, an initialize ml_init(int), a call to send it a binary array, a call to act on it, and call to close. This is on an rPi (Linux), and I've used swig to build the intermediate files.

The wrapper file is being made as a .cpp file, and it's resulting .o file is included in the link line.

Everything seems to compile and link just fine, but when I run my test perl app, I get undefined symbol: _Z7ml_initi. I have used nm on the resulting .so file, and ml_init is listed with a hex value and a T. However, the type-safe mangled name (which is what is coming up in the error), is also listed, but it has a U in front of it. The man page for nm states this means the symbol is "undefined".

HUH?

If it's there, in the file, that means it's defined, right? How can it be present, yet not defined to the linker?

The lo-fi way I search the perldocs on the command line

r/perl

Published by /u/briandfoy on Wednesday 06 November 2024 12:31

There's a command-line doc-searching thing I often, being a command-line sorta person, and I keep meaning to share it. If you like being in the browser most of the time, perldoc.perl.org will get you the same thing. I just happen to live most of my life in a terminal because that's what I like.

The Perl docs are comprehensive, but sometimes its difficult to find (or remember) where something is. For example, where do you look for the docs on perl's variable types? If you knew nothing about Perl and just saw the list of doc names, you might think it's perlvar. There are other examples. It's not a big deal because there are plenty of ways to search free text.

This came up again on a Stackoverflow in Why does Perl assign a hash reference as value for a non-existent key?. I left a comment with unix pipeline with a couple of xargs:

$ perldoc -l perldata | xargs dirname | xargs grep -R -I autovivification 

I could probably make this an alias too, but so far I haven't. This is mostly because I get my search result and move on in life, screwing over future me by not being sufficiently Lazy:

$ alias p="perldoc -l perldata | xargs dirname | xargs grep -R -i" $ p autovivification 

Since I have many perls installed with versioned tools, I can search different versions of the docs, which I do quite a bit:

$ perldoc5.28.0 -l perldata | xargs dirname | xargs grep -R -I autovivification 

perldoc.perl.org has a version switcher too, which is very nice.

The -l returns a location, and I know that all the core docs are in the same directory, which is just another thing I know that someone new wouldn't guess. The output is the path:

/usr/share/perl5/core_perl/pod/perldata.pod 

The dirname takes off the file portion to leave /usr/share/perl5/core_perl/pod, which I'll later use with grep -R. If you don't have that (it seems to be everywhere I normally use), there's on in PerlPowerTools. There's probably one in WSL too, but if you are using Strawberry, this will probably find the WSL version.

I sometimes use -l to find where Perl finds some module, often in the case where the module search path is not what I thought it was:

$ perldoc -l Some::Module 

Back to

The easy thing to do is search perldoc.perl.org, which gives good results. Of course, to search this in either method, you have to know that your search term is even a thing. There's no reason that anyone starting with Perl would know "autovivification" was the term they wanted (unless they read Intermediate Perl).

In this particular case, the docs could do a lot better with "autovivification" since there's a section title with that name that says almost nothing about it, but an explanation shows up later. Sometimes docs (and not just in Perl) are just that way. One of my favorite sayings about docs is that Perl has unorganized, complete docs while Python (and others) have organized, incomplete docs. That's a different post though.

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

I am using Perl5 (revision 24 subversion 1) on linux.

use strict;
use warnings;

my $fruit_colors = {
        'apple' => {'red' => 'good'}
};

print($fruit_colors->{'orange'}); # this prints nothing

print($fruit_colors->{'orange'}{'orange'}); # this prints nothing too

print($fruit_colors->{'orange'}); # but this suddenly prints 'HASH(0x1f63098)'


My question is why does this happen? and how to prevent it from causing unintential consequences.

Celebrating 14 years of Rex with Rex-1.15.0 release

r/perl

Published by /u/erkiferenc on Tuesday 05 November 2024 19:51

Happy 14th birthday, Rex! 🎂

To celebrate the occasion, I released version 1.15.0 of Rex, the friendly automation framework on CPAN.

This minor release contains several bug fixes and few new features.

Warm welcome to our new contributors, Robert Rothenberg and Alexander Karelas!

Special thanks to Ctrl O Ltd for sponsoring Rex maintenance!

Release notes | Changes | Toot

Happy hacking!

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

sv_pos_2ub_forwards: Replace rolled-own with utf8_hop

Perl commits on GitHub

Published by khwilliamson on Tuesday 05 November 2024 18:45

sv_pos_2ub_forwards: Replace rolled-own with utf8_hop

"Hackable" Email - Extending Postfix with Wasm & Perl

r/perl

Published by /u/nilslice on Tuesday 05 November 2024 16:58

How do I use a JOIN in Perl's DBIx::Class

Perl questions on StackOverflow

Published by Peter on Tuesday 05 November 2024 10:49

Some time ago I worked my way trough a Node JS tutorial which leaned heavy on using an ORM to access the database. Allthough I did not like Node JS at all (it's just not for me) I did fancy the ORM concept. Perl being my scripting lingo of choice I decided to dive into DBIx::Class, or DBIC. And I kinda got stuck when trying to access related data, using joins.

I'm working my way trough the MAN pages and am currently reading DBIx::Class::Manual::Joining

Created myself a sqlite database:

CREATE TABLE IF NOT EXISTS `cd` (
        `id` integer primary key NOT NULL UNIQUE,
        `cd_title` TEXT NOT NULL UNIQUE,
        `year` Text Not Null
);
CREATE TABLE IF NOT EXISTS `track` (
        `id` integer primary key NOT NULL UNIQUE,
        `cd_id` INTEGER NOT NULL,
        `track_title` TEXT NOT NULL UNIQUE,
        FOREIGN KEY(`cd_id`) REFERENCES `cd`(`id`)
);

Insert Into cd (id, cd_title, year) Values
        (1, 'CD 1', '2004'),
        (2, 'CD 2', '1995'),
        (3, 'CD 3', '2014'),
        (4, 'CD 4', '2024')
;
Insert Into track (id,cd_id,track_title) Values
        (1,1,'Track 1 CD 1'),
        (2,1,'Track 2 CD 1'),
        (3,1,'Track 3 CD 1'),
        (4,1,'Track 4 CD 1'),
        (5,1,'Track 5 CD 1'),
        (6,2,'Track 1 CD 2'),
        (7,2,'Track 2 CD 2'),
        (8,2,'Track 3 CD 2'),
        (9,3,'Track 1 CD 3'),
        (10,3,'Track 2 CD 3'),
        (11,3,'Track 3 CD 3'),
        (12,3,'Track 4 CD 3'),
        (13,3,'Track 5 CD 3'),
        (14,4,'Track 2 CD 4'),
        (15,4,'Track 3 CD 4'),
        (16,4,'Track 4 CD 4'),
        (17,4,'Track 5 CD 4')
;

In essence 4 CDs each of them with a couple of tracks. Schema files were made using dbicdump:

 dbicdump -o dump_directory=. Model::Schema dbi:SQLite:cds.sqlite

The schema files are kinda long, I'll spare you those. But since dbicdump made them I'm assuming them to be correct.

After that I wrote myself a little test script:

#! /usr/bin/env perl

use v5.20;
use Data::Dumper;
use DBIx::Class;
use lib '.';
use Model::Schema qw();
my $schema = Model::Schema->connect('dbi:SQLite:cds.sqlite');


my $cds = $schema->resultset('Cd')->search(
        {
                'cd_title' => { like => 'CD%'}
        },
        {

                join => 'tracks',
                order_by => ['tracks.id'],
        }
);

for my $cd ($cds->all()){
        say $cd->cd_title;
        say $cd->get_column('track_title');
}

Sort of like how the MAN page says. But I can't get it to work!

CD 1
DBIx::Class::Row::get_column(): No such column 'track.track_title' on Model::Schema::Result::Cd at ./test.pl line 24

shell returned 2

It keeps complaining that it can't find the column 'track_title' in the 'track' table. I allready tried all sort of variation of the column name. Like putting the table name in it like 'track.track_title', but reading the error message it seems to be doing that on its own anyway.

It does seem to get all the data. When I leave out the second 'say' line it does in fact print out the CD title for every track. The 'join' seems in fact to be working.

Checking the 'Track.pm' schema file I see the following columns being added:

__PACKAGE__->add_columns(
  "id",
  { data_type => "integer", is_auto_increment => 1, is_nullable => 0 },
  "cd_id",
  { data_type => "integer", is_foreign_key => 1, is_nullable => 0 },
  "track_title",
  { data_type => "text", is_nullable => 0 },
);

One other thing I noticed: The example in the MAN page uses a sort on 'tracks.id'. Where 'tracks' is the relation name, not the table name. Which is why I tried '$cd->get_column('tracks.track_title')' in the say, to no effect.

I really would like to take this hurdle.

Peter

perl.h: Add comments regarding UTF-8 conversion table

Perl commits on GitHub

Published by khwilliamson on Monday 04 November 2024 18:00

perl.h: Add comments regarding UTF-8 conversion table

UTF-8 is one of several sanctioned ways of encoding Unicode "code
points".  But a code point is, at its heart, just a non-negative integer.
The mechanism of UTF-8 can't handle numbers 2**36 and higher.  (And
Unicode and other standards artificially limit what numbers are
considered acceptable.)

Perl decided to create an extension to UTF-8 for representing higher
values, so it could be used for any 64-bit number.

We now have a DFA that translates UTF-8 for numbers less than 2**36.
For larger numbers, a different mechanism (the older one) is used.
The DFA uses table lookup.  To get it to accept larger numbers, the
table would have to be widened from U8 to U16 (and the numbers in it
recalculated).

The table is about 180 bytes now.  Widening it wouldn't consume that
many more bytes in the grand scheme of things, but I don't know of
anyone actually using these extremely large numbers, so I haven't felt
that it is worth it.

But every so often, I get curious about what it would take, so this
commit sketches that out, for possible future reference.

makedef.pl: Synchronize with perl.h

Perl commits on GitHub

Published by khwilliamson on Monday 04 November 2024 17:59

makedef.pl: Synchronize with perl.h

There are a couple of places in perl.h that need to be converted to perl
and copied to makedef.  It's easy to forget to do this when updating it;
and this commit corrects one such omission.

Perl Weekly #693 - Advertising Perl

dev.to #perl

Published by Gabor Szabo on Monday 04 November 2024 06:41

Originally published at Perl Weekly 693

Hi there!

Throughout the years I had many brilliant ideas regarding Perl and the Perl community. I know they were brilliant because, as I found out later, they were already done by Dave Cross before me. This always gave me mixed feelings. On one hand it was always rather disappointing that my ideas weren't new or original. On the other hand it was of a great pride that my ideas aren't that dumb if Dave also had them.

Today I think I can celebrate. I think this is the first time where I had the idea (and the implementation) first.

In a recent article Dave writes about Advertising Perl. A very good idea to use the existing platforms to advertise Perl events. As I can see it is exactly 10 years after I announced shutting down the Perl Community Adserver. Wow, I am rather shocked that so many years have passed and unfortunately I can't find the posts in which I started to talk about it so I can't really verify the timeline.

In any case, I hope his attempt will be more successful than mine was.

Enjoy your week!

--
Your editor: Gabor Szabo.

Announcements

Perl and Raku Conference 2025 News

It will take place June 27-29, 2025 in Greenville, South Caroline

Articles

A Regexp::Debugger visualization for Abigail's prime number checker

Do you know how to generate prime numbers using a Regular Expression?

Advertising Perl

About the creation of the Perl Ad Server

London Perl & Raku Workshop 2024

LPW 2024

My London Perl And Raku Workshop 2024

London Perl & Raku Workshop 2024: Quick Afterwords

Perl

This week in PSC (166) | 2024-10-31

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 - 294

Welcome to a new week with a couple of fun tasks "Consecutive Sequence" and "Next Permutation". 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 - 293

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

TWC293

Yet another compact and elegant solutions in Perl. You must checkout if you are Perl fans.

Boomerang or Similar

Cool use of subset of Raku giving us the elegant solutions. Great work, keep it up.

Taking A New Angle

Here is another gem from CPAN, Math::Trig. The end result is worth checking out. Thanks for sharing.

Perl Weekly Challenge: Week 293

We all know the compact solution in Raku but replicating the same in Perl is awesome, very impressive. Keep sharing.

Perl Weekly Challenge 293: Similar Dominoes

Comparative approach to a task in Perl and Raku is never to be missed. It always special for me. Thanks for sharing knowledge.

Perl Weekly Challenge 293

Master of in-house Perl one-liners came up with yet another creative solution. Highly recommended.

Domino Frequencies and the Vectorized Boomerang

Any maths lover? I am one, so loved the pure mathematical approach and narrative. Cool work, keep it up.

Oh, oh, Domino!

Nice to see, how to deal edge cases. Very brave move and that too in multiple languages.

Matching and returning

Another mathematical angle to deal with Boomerang task. And on top, DIY tool is handy to play with.

The Weekly Challenge #293

Modularised approach makes the solution easy to read and follow. Short and concise narration comes handy. Great work.

Domino Boomerang

Python is my new love and it doesn't take any effort to decode it. Credit goes to the master, Roger.

Similar boomerang

Keep it sweet and simple, yet end up with classic end result. This is for both Perl and Python lovers.

Weekly collections

NICEPERL's lists

Great CPAN modules released last week.

Events

Boston.pm monthly meeting

November 12, 2024, Virtual event

Purdue Perl Mongers

November 13, 2024, Virtual event

Toronto Perl Mongers monthly meeting

November 28, 2024, Virtual event

Purdue Perl Mongers

December 11, 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.

Blog

The Weekly Challenge

Published on Monday 04 November 2024 05:45

TABLE OF CONTENTS 01. HEADLINES 02. STAR CONTRIBUTORS 03. CONTRIBUTION STATS 04. GUESTS 05. LANGUAGES 06. CENTURION CLUB 07. DAMIAN CONWAY’s CORNER 08. ANDREW SHITOV’s CORNER 09. PERL SOLUTIONS 10. RAKU SOLUTIONS 11. PERL & RAKU SOLUTIONS HEADLINES Thank you Team PWC for your continuous support and encouragement. STAR CONTRIBUTORS Following members shared solutions to both tasks in Perl and Raku as well as blogged about it.

Perl

The Weekly Challenge

Published on Monday 04 November 2024 05:45

TABLE OF CONTENTS 01. HEADLINES 02. STAR CONTRIBUTORS 03. CONTRIBUTION STATS 04. GUESTS 05. LANGUAGES 06. CENTURION CLUB 07. DAMIAN CONWAY’s CORNER 08. ANDREW SHITOV’s CORNER 09. PERL SOLUTIONS 10. RAKU SOLUTIONS 11. PERL & RAKU SOLUTIONS HEADLINES Thank you Team PWC for your continuous support and encouragement. STAR CONTRIBUTORS Following members shared solutions to both tasks in Perl and Raku as well as blogged about it.

The Weekly Challenge - Perl & Raku

The Weekly Challenge

Published on Monday 04 November 2024 05:45

The page you are looking for was moved, removed, renamed or might never existed.

Raku

The Weekly Challenge

Published on Monday 04 November 2024 05:45

TABLE OF CONTENTS 01. HEADLINES 02. STAR CONTRIBUTORS 03. CONTRIBUTION STATS 04. GUESTS 05. LANGUAGES 06. CENTURION CLUB 07. DAMIAN CONWAY’s CORNER 08. ANDREW SHITOV’s CORNER 09. PERL SOLUTIONS 10. RAKU SOLUTIONS 11. PERL & RAKU SOLUTIONS HEADLINES Thank you Team PWC for your continuous support and encouragement. STAR CONTRIBUTORS Following members shared solutions to both tasks in Perl and Raku as well as blogged about it.

Nelua

The Weekly Challenge

Published on Monday 04 November 2024 05:45

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.

Perl and Raku Conference 2025 News!

r/perl

Published by /u/GeekRuthie on Sunday 03 November 2024 17:36

Similar boomerang

dev.to #perl

Published by Simon Green on Sunday 03 November 2024 12:58

Weekly Challenge 293

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: Similar Dominos

Task

You are given a list of dominos, @dominos.

Write a script to return the number of dominoes that are similar to any other domino.

$dominos[i] = [a, b] and $dominos[j] = [c, d] are same if either (a = c and b = d) or (a = d and b = c).

My solution

I'm not sure if it's a British/US English thing or something else, but I'm using Dominoes as the plural of Domino. Dominos what what you get when you are hungry.

For this task, I take integers from the command line and convert them to a list of lists (arrays of arrays in Perl). If this was an actual real-world project, I'd probably use a Dataclass, and have an equality operator.

I have a double loop. The outer loop - called i - is from 0 to one less than the number of dominoes. The inner loop - called j - is also the same. I skip the case when i and j are the same. If the dominoes at position i and j are the same (either same number or opposite numbers), I add one to count and exit the inner loop.

def similar_dominoes(dominoes: list) -> int:
    count = 0

    for i in range(len(dominoes)):
        for j in range(len(dominoes)):
            if i == j:
                continue
            if (dominoes[i][0] == dominoes[j][0] and dominoes[i][1] == dominoes[j][1]) \
                    or (dominoes[i][0] == dominoes[j][1] and dominoes[i][1] == dominoes[j][0]):
                count += 1
                break

    return count

Examples

$ ./ch-1.py 1 3 3 1 2 4 6 8
2

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

Task 2: Boomerang

Task

You are given an array of points, (x, y).

Write a script to find out if the given points are a boomerang.

A boomerang is a set of three points that are all distinct and not in a straight line.

My solution

Like with the last task, I take integers from the command line and convert them to a list of lists (arrays of arrays in Perl).

I remember enough from high school math to know we can get the slope (gradient) of two points with the formula (x2 - x1) ÷ (y2 - y1). However if y1 and y2 are the same, we get a division by zero error.

Therefore I use the following checks:

  1. If all y values (second item in each list) are the same, return False as the points make a flat line.
  2. If any y values are the same as the first y value, return True (as we know at least one y value is different).
  3. Calculate the absolute slop between the first point and the other points using the above formula. Store this as a set. Sets don't store duplicate values.
  4. If the set only has one value, it's a straight line and return False. If there is more than one value, then it's a boomerang. I'm not here to determine if it is a good boomerang :)
def is_boomerang(points: list) -> bool:
    if all(points[0][1] == points[i][1] for i in range(1, len(points))):
           return False

    if any(points[0][1] == points[i][1] for i in range(1, len(points))):
           return True

    degrees = set(abs((points[0][0] - points[i][0]) / (points[0][1] - points[i][1])) for i in range(1, len(points)))
    return False if len(degrees) == 1 else True

Examples

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

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

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

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

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

$ ./ch-2.py 0 0 2 3 4 5
true

Perl and Raku Conference 2025 News

Perl Foundation News

Published by D Ruth Holloway on Sunday 03 November 2024 12:00



The conference organizing team is excited to present details of the 2025 Perl and Raku Conference, to be held June 27-29 in Greenville, SC. Registration for the conference will open soon, but you can start planning now to attend. We'd love to see you in the Palmetto State next summer!

Streamlined conference, new schedule!

The Perl and Raku Conference 2025 is changing things up a little. We're streamlining the conference and its venue, and focusing on the best of the best presenters. The conference will begin on Friday, June 27, 2025, with an all-day class. That evening, the Arrival Dinner and Anti-Arrival dinners. Saturday morning the 28th, the conference proper kicks off with a great keynote from someone new to our conference, followed up by BOFs and breakout sessions across the rest of Saturday and Sunday the 29th.

Every morning of the conference, around the breakfast area of the hotel, and outside the breakout rooms, look for your copy of Update::Daily, our daily newsletter which will have the latest updates on sessions for the day, news about after-hours events, and articles about our sponsors and speakers.

Keynoter confirmed

Our keynote this year will be presented by David Both, who is an Open Source Software and GNU/Linux advocate, trainer, writer, and speaker. He has been working with Linux and Open Source Software since 1996 and with computers since 1969. He is a strong proponent of and evangelist for the “Linux Philosophy for System Administrators.” With his wealth of experience and expertise, he'll be bringing us thoughts on the Linux Philosophy as it applies to developers and system administrators. Be sure to join us for his talk!

Hotel registration open now!

Our conference hotel is the Holiday Inn Express and Suites, on Woodruff Rd in Greenville, SC. We have about half of the hotel reserved in our block, which is now open for registrations. You can find rates and details of our accommodations on the Conference website.

CFP open now!

The Call for Presentations is open now. Because of our streamlined format and shorter conference in 2025, speaking slots will be more competitive than in past years. If you'd like to present, check out the Call for Presentations today, and get yours entered. Speakers will be announced beginning in late January.

Perl Books for Cybersecurity Professionel

r/perl

Published by /u/fosres on Sunday 03 November 2024 01:34

Hello!

Security Engineers often must use scripting for task automation.

I decided to use Perl to do this. If you are a cybersecurity professionel what books and online resources would you recommend I read to learn more?

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

Perl Weekly Challenge 293: Similar Dominoes

blogs.perl.org

Published by laurent_r on Saturday 02 November 2024 21:47

These are some answers to the Week 293, Task 1, 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 November 3, 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 1:

You are given a list of dominoes, @dominoes.

Write a script to return the number of dominoes that are similar to any other domino.

$dominoes[i] = [a, b] and $dominoes[j] = [c, d] are same if either (a = c and b = d) or (a = d and b = c).

Example 1

Input: @dominoes = ([1, 3], [3, 1], [2, 4], [6, 8])
Output: 2

Similar Dominoes: $dominoes[0], $dominoes[1]

Example 2

Input: @dominoes = ([1, 2], [2, 1], [1, 1], [1, 2], [2, 2])
Output: 3

Similar Dominoes: $dominoes[0], $dominoes[1], $dominoes[3]

First, I would say that dominoes (1, 3) and (3,1) are not really similar, they are equal, they are the same domino seen from a different angle.

Then we are not said what to do when you have for example dominoes (1, 3), (3,1), (2,4) and (4,2), i.e. two pairs of "similar" dominoes. And the examples provided don't clarify this case. I'll consider that, in that case, we have 4 similar dominoes, even if they are similar two by two.

To make things simple, I've chosen to represent dominoes as simple strings: rather than having a pair of integers such as (3,1), I'll use the string "31". Common domino sets have square ends with 0 (blank) to 6 spots. So this representation is sufficient and not ambiguous. There are, however, some extended domino sets with square ends having more than 6 spots. In the event that there are more than 9 spots (I've never seen that, but it could happen), we would need to change an input tile representation to a string with a separator, for example 11-13, and slightly modify the sort-dom subroutine accordingly (but the change is really simple).

Similar Dominoes in Raku

The first thing this program does is to "normalize" tiles, i.e. reorganize them so that the tiles square ends always appear in ascending order (done by the sort-dom subroutine). Once this is done, we simply need to count the dominoes of each type (done in the $histo histogram) and finally count the histogram values greater than 1. The $histo data structure is a Bag, i.e. an immutable collection of distinct objects with integer weights.

sub sort-dom ($dom) {
    my ($a, $b) = $dom.comb;
    return $a < $b ?? "$a$b" !! "$b$a";
}

sub similar-dom (@doms) {
    my $histo = bag map { sort-dom $_ }, @doms;
    my $count = 0;
    $count += $_ for grep { $_ > 1 }, $histo.values;
    return $count;
}

my @tests = <13 31 24 68>, <12 21 11 12 22>, <31 24 13 56 24>;
for @tests -> @test {
    printf "%-15s => ", "@test[]";
    say similar-dom @test;
}

This program displays the following output:

$ raku ./similar-dominoes.raku
13 31 24 68     => 2
12 21 11 12 22  => 3
31 24 13 56 24  => 4

Similar Dominoes in Perl

This is a port to Perl of the above Raku program. The only significant difference is that it uses a hash instead of a Bag. Please refer to the above two sections if you need explanations.

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

sub sort_dom  {
    my $dom = shift;
    my ($a, $b) = split //, $dom;
    return $a < $b ? $dom : "$b$a";
}

sub similar_dom {
    my %histo;  
    $histo{$_}++ for map { sort_dom $_ } @_;
    my $count = 0;
    $count += $_ for grep { $_ > 1 } values %histo;
    return $count;
}

my @tests = ( [<13 31 24 68>], [<12 21 11 12 22>], 
                [<31 24 13 56 24>] );
for my $test (@tests) {
    printf "%-15s => ", "@$test";
    say similar_dom @$test;
}

This program displays the following output:

$ perl ./similar-dominoes.pl
13 31 24 68     => 2
12 21 11 12 22  => 3
31 24 13 56 24  => 4

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 November 10, 2024. And, please, also spread the word about the Perl Weekly Challenge if you can.

Perl to find AND replace IP address in a string

Perl questions on StackOverflow

Published by dms666 on Saturday 02 November 2024 21:24

I need help for a Perl script to find and replace an IP address saved to a string or in a file, if an IP address is present.

Apologies first - I don't have a development/software background but have managed to update and modify the few Perl scripts that have fallen in my lap by research and trial and error. I was hesitant to post, however, the solution to this programming task simply eludes me.

I have seen a few examples of finding and extracting an IP address, see below for an example using . But I haven't figured out how to apply to Regexp::Common:net to read from a string or a file.

#!/usr/bin/perl -w

use strict;
use warnings;
use Regexp::Common qw/net/;

my $Event_text="This is a test string with an IP address 10.10.10.20"

while (<DATA>)
{
    print $1, "\n" if /($RE{net}{IPv4})/;
}

__DATA__
10.10.10.10

Executing this does return '10.10.10.10' and it ignores non-valid IPs but I still need the script to: (a) search in a string already saved to a variable or a file (one or the other - doesn't matter) (b) somehow replace this IP address with some other string, like X.X.X.X within the given string or file (again, one or the other). I assume this can be done with a Perl search and replace regexp - which is another matter.

The Perl script I tested works but it's only a portion of what I need and was really just to understand how the Regexp::Common (net) module works.

(dxx) 11 great CPAN modules released last week

Niceperl

Published by Unknown on Saturday 02 November 2024 21:32

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

  1. Alien::Build - Build external dependencies for use in CPAN
    • Version: 2.84 on 2024-10-29, with 22 votes
    • Previous CPAN version: 2.83 was 4 months, 24 days before
    • Author: PLICEASE
  2. App::cpanminus - get, unpack, build and install modules from CPAN
    • Version: 1.7048 on 2024-10-29, with 281 votes
    • Previous CPAN version: 1.7047 was 1 year, 2 months, 30 days before
    • Author: MIYAGAWA
  3. App::DBBrowser - Browse SQLite/MySQL/PostgreSQL databases and their tables interactively.
    • Version: 2.416 on 2024-10-28, with 14 votes
    • Previous CPAN version: 2.415 was 1 month, 23 days before
    • Author: KUERBIS
  4. App::Netdisco - An open source web-based network management tool.
    • Version: 2.080003 on 2024-10-30, with 16 votes
    • Previous CPAN version: 2.079001 was 1 month, 17 days before
    • Author: OLIVER
  5. DBIx::Class::Candy - Sugar for your favorite ORM, DBIx::Class
    • Version: 0.005004 on 2024-10-29, with 21 votes
    • Previous CPAN version: 0.005003 was 7 years, 3 months, 15 days before
    • Author: WESM
  6. DBIx::Lite - Chained and minimal ORM
    • Version: 0.36 on 2024-10-31, with 28 votes
    • Previous CPAN version: 0.35 was 1 month, 13 days before
    • Author: AAR
  7. Image::ExifTool - Read and write meta information
    • Version: 13.00 on 2024-10-29, with 42 votes
    • Previous CPAN version: 12.76 was 8 months, 29 days before
    • Author: EXIFTOOL
  8. PDL - Perl Data Language
    • Version: 2.094 on 2024-11-02, with 57 votes
    • Previous CPAN version: 2.093 was 1 month, 3 days before
    • Author: ETJ
  9. SPVM - The SPVM Language
    • Version: 0.990026 on 2024-11-01, with 33 votes
    • Previous CPAN version: 0.990025001 was 7 days before
    • Author: KIMOTO
  10. Sys::Virt - libvirt Perl API
    • Version: v10.9.0 on 2024-11-01, with 17 votes
    • Previous CPAN version: v10.6.0 was 2 months, 26 days before
    • Author: DANBERR
  11. Term::Choose - Choose items from a list interactively.
    • Version: 1.767 on 2024-10-28, with 15 votes
    • Previous CPAN version: 1.765 was 5 months, 26 days before
    • Author: KUERBIS

PWC 293 Similar Dominos Done Badly

dev.to #perl

Published by Bob Lied on Saturday 02 November 2024 12:58

Perl Weekly Challenge 293 gave us a problem that didn't really look that hard, yet I did it wrong at least three times before finishing. It reminded me of the song How to Save a Life, where the refrain goes "Where did I go wrong?"

The Task

You are given a list of dominos, @dominos. 
Write a script to return the number of 
dominoes that are similar to any other domino.

$dominos[i] = [a, b] and $dominos[j] = [c, d]
are the same if either (a = c and b = d) or
(a = d and b = c).

Example 1

  • Input: @dominos = ([1, 3], [3, 1], [2, 4], [6, 8])
  • Output: 2
  • Similar Dominos: $dominos[0], $dominos[1]

Example 2

  • Input: @dominos = ([1, 2], [2, 1], [1, 1], [1, 2], [2, 2])
  • Output: 3
  • Similar Dominos: $dominos[0], $dominos[1], $dominos[3]

Bad Start

First thought: oh, this is one of those compare-all-pairs problems. Double loop, count up the matches. Simple.

my $count = 0;
while ( defined(my $d1 = shift @dominos) )
{
    for my $d2 ( @dominos) 
    {
        if ( ( $d1->[0] == $d2->[0] && $d1->[1] == $d2->[1] )
          || ( $d1->[0] == $d2->[1] && $d1->[1] == $d2->[0] ) )
        {
            $count++;
        }
    }
}
return $count;

Nope. This double-counts the pairs in Example 2. The first time through the loop it finds the three similar dominoes, but then it loops again and finds the matching pair 1 and 3.

Strike 2

Okay, so we need to remove an element from consideration once it's been noted as similar. Let's delete the second member of the pair when we find a match. Annoyingly, I now need to know the index of the matches, but I can take advantage of the indexed feature that was added to Perl a couple of releases ago.

my $count = 0;
while ( defined(my $d1 = shift @dominos) )
{
    for my ($i, $d2) ( indexed @dominos ) 
    {
        if ( ( $d1->[0] == $d2->[0] && $d1->[1] == $d2->[1] )
          || ( $d1->[0] == $d2->[1] && $d1->[1] == $d2->[0] ) )
        {
            $count++;
            delete $dominos[$i];
        }
    }
}
return $count;

Derp. delete replaces the deleted element with an undef, so now the program dies by trying to reference an undefined array element. I need to add code to check for undef. Not very demure; not very mindful.

Strike 3

Easy enough. Instead of delete, use splice. That will compress the deleted element out of the array -- no undef checking needed.

[...]
while ( ... ) {
    for ... {
        if ( ... ) {
            count++;
            splice(@dominos, $i, 1);
        }

Fail. splice does indeed remove the element of the array, but doing that resets the indexes, so my $i index variable is now pointing at the wrong element after the operation, so I'll be skipping some pairs.

Engage Brain

Finally, it dawns on me that pair-wise checking may not be the way to go here. What if we enter the dominoes into a hash, and count the frequencies that way? All we have to do is force dominoes to look similar by always listing the smaller dots first.

sub similar(@dominos)
{
    my %count;
    while ( defined( my $tile = shift @dominos ) )
    {
        my @d = $tile->@*;
        @d = ($d[1], $d[0]) if $d[1] < $d[0];

        $count{ "[$d[0],$d[1]]" }++;
    }
    return sum0 values %count;
}

That looks better. We're only making one pass over the list, and O(1) is always nice. We form a key for the hash that has the pair of numbers in a string, which is going to be useful for debugging, if we need to dump the hash table (but surely we have it right now). Retrieving the counts is easy with applying values to the hash, and List::Util::sum0 will add them up.

And ... nope, still a bug. The hash now contains dominoes that are unique. We need to add a little filter to only count dominoes that show up at least twice.

[...]
    return sum0 { grep $_ > 1 } values %count;

Good grief. Finally, something I'm willing to push to Github

Advertising Perl

Perl Hacks

Published by Dave Cross on Friday 01 November 2024 15:10

Last weekend, we had a very successful (and very enjoyable) London Perl Workshop. After a five-year break, it was great to see so many old faces again. But in addition to people who had been regular attendees at recent workshops, two other groups of people were there in large numbers—people who had moved away from the Perl community (and who were coming back for the nostalgia) and new Perl users who hadn’t been to any Perl conference before. In both cases, it seems that one marketing move was particularly effective at telling both of these groups about the workshop.

It was a small, text advert that ran on MetaCPAN.

I had nothing to do with the organisation of the workshop, so I have no idea who had the idea of running that ad, but it was (like so many great ideas) obvious in retrospect. It’s great to publish blog posts about upcoming events and mention events in the Perl Weekly newsletter. But marketing like that is mostly going to be read by people who are already part of the Perl community. And they (hopefully) already know about the workshop.

Whereas, sites like MetaCPAN are visited by Perl programmers who don’t consider themselves part of the community. People who don’t attend Perl Mongers meetings. People who don’t read blogs.perl.org. People who are (to use terminology that has been used to explain this problem for about twenty years) outside the echo chamber.

Advertising Perl community events to as large an audience as possible is a really good idea, and I think we should do more of it. But it has its downsides. Someone has to do some work to create a pull request to add the advert (and another one to remove it once the event is over). That’s not hard, but it requires thought and planning. I started to wonder if we could simplify this process and, in doing so, encourage more people to run ads like these on sites where more people might see them.

After an hour or so, I had a prototype of the Perl Ad Server – which I have subsequently cleaned up and improved.

It’s a simple enough concept. You add a tiny fragment of Javascript to your website. And that then automatically adds a small banner ad to the top of your site. We can control the ads that are being promoted by simply editing the JSON that we serve to the client sites.

It’s experimental. So I’d like to get as many people as possible to try it out.

It comes with a tiny caveat. I’m neither a web designer nor a Javascript expert. So it may interact with some web frameworks in weird ways (I added it to CPAN Dashboard and the ad appeared under the navbar – which isn’t supposed to happen). If it doesn’t work with your site for some reason, please remove the Javascript and raise an issue so I can investigate.

And if you’d like your event added to the current list of ads, let me know too.

The post Advertising Perl appeared first on Perl Hacks.

Advertising Perl

dev.to #perl

Published by Dave Cross on Friday 01 November 2024 15:10

Last weekend, we had a very successful (and very enjoyable) London Perl Workshop. After a five-year break, it was great to see so many old faces again. But in addition to people who had been regular attendees at recent workshops, two other groups of people were there in large numbers—people who had moved away from the Perl community (and who were coming back for the nostalgia) and new Perl users who hadn’t been to any Perl conference before. In both cases, it seems that one marketing move was particularly effective at telling both of these groups about the workshop.

It was a small, text advert that ran on MetaCPAN.

I had nothing to do with the organisation of the workshop, so I have no idea who had the idea of running that ad, but it was (like so many great ideas) obvious in retrospect. It’s great to publish blog posts about upcoming events and mention events in the Perl Weekly newsletter. But marketing like that is mostly going to be read by people who are already part of the Perl community. And they (hopefully) already know about the workshop.

Whereas, sites like MetaCPAN are visited by Perl programmers who don’t consider themselves part of the community. People who don’t attend Perl Mongers meetings. People who don’t read blogs.perl.org. People who are (to use terminology that has been used to explain this problem for about twenty years) outside the echo chamber.

Advertising Perl community events to as large an audience as possible is a really good idea, and I think we should do more of it. But it has its downsides. Someone has to do some work to create a pull request to add the advert (and another one to remove it once the event is over). That’s not hard, but it requires thought and planning. I started to wonder if we could simplify this process and, in doing so, encourage more people to run ads like these on sites where more people might see them.

After an hour or so, I had a prototype of the Perl Ad Server – which I have subsequently cleaned up and improved.

It’s a simple enough concept. You add a tiny fragment of Javascript to your website. And that then automatically adds a small banner ad to the top of your site. We can control the ads that are being promoted by simply editing the JSON that we serve to the client sites.

It’s experimental. So I’d like to get as many people as possible to try it out.

It comes with a tiny caveat. I’m neither a web designer nor a Javascript expert. So it may interact with some web frameworks in weird ways (I added it to CPAN Dashboard and the ad appeared under the navbar – which isn’t supposed to happen). If it doesn’t work with your site for some reason, please remove the Javascript and raise an issue so I can investigate.

And if you’d like your event added to the current list of ads, let me know too.

The post Advertising Perl appeared first on Perl Hacks.

This week in PSC (166) | 2024-10-31

blogs.perl.org

Published by Perl Steering Council on Friday 01 November 2024 06:36

We were joined by Leon Timmermans and Tim Legge to discuss plans for TLS support in core.

  • We talked about our inadequate handling of point releases and especially security releases. In the past this was handled on individual initiative. We need to institutionalize at least some of this as actual process to keep things on the rails.
  • We discussed with Leon and Tim what we want to do to have TLS support in core. Future support for underlying APIs other than OpenSSL is desirable. Net::SSLeay also has cruft that we would prefer to avoid in core.

[P5P posting of this summary]

Domino Frequencies and the Vectorized Boomerang (PWC 293)

dev.to #perl

Published by Matthias Muth on Thursday 31 October 2024 23:12

Challenge 293 solutions in Perl by Matthias Muth

Summary

Similar Dominos:
Two lines of code to compute frequencies of Domino value combinations
and then to sum them up.

Boomerang:
Thank you for helping me to get a refresher in vector geometry!
It only needs two formulas and one comparison for checking whether the input points form a 'boomerang', using integer arithmetics only (no divisions, no square roots).

Code:
Find the complete source code for both tasks, including tests, on Github.

Task 1: Similar Dominos

You are given a list of dominos, @dominos.
Write a script to return the number of dominos that are similar to any other domino.
$dominos[i] = [a, b] and $dominos[j] = [c, d] are same if either (a = c and b = d) or (a = d and b = c).

Example 1
Input: @dominos = ([1, 3], [3, 1], [2, 4], [6, 8])
Output: 2
Similar Dominos: $dominos[0], $dominos[1]

Example 2
Input: @dominos = ([1, 2], [2, 1], [1, 1], [1, 2], [2, 2])
Output: 3
Similar Dominos: $dominos[0], $dominos[1], $dominos[3]

My thinking process:

  • For counting the number of similar dominos, we can first count for each distinct value combination how often it exists, and then sum up the numbers of those that exist more than once.
  • Counting how often each value combination exists is the same as getting their frequencies. That's something we've done quite often before. In Perl typically a hash is used, with the domino combination as the key, and the frequency as the value. Today, I will let List::MoreUtils do the job of creating the frequency hash. Less typing ;-).
  • To use the two numbers on a domino as a key, we have to combine them into a string. Let's join the two numbers with a separator (like '-') in between them.
  • A combination and its inverse (like [3, 1] and [1, 3]) should be considered as being equal. They need to be mapped to the same key. To get that, it's easiest to just sort the two numbers (even if there are only two of them) before turning them into a key string. Both dominos [3, 1] and [1, 3] will then be counted using "1-3" as the key.
  • The type of sort (numerical or lexical, ascending or descending) does not matter at all, it is only important that the result is the same if the input is in reversed order. The default lexical sort will therefore do nicely.
  • Once we have the frequencies, we add them up, but we exclude those having a frequency of 1. (The frequencies are in the values of the frequency hash.)

My solution then is this little program:

use v5.36;
use List::MoreUtils qw( frequency );
use List::Util qw( sum );

sub similar_dominos( $dominos ) {
    my %frequencies = frequency( map { join "-", sort $_->@* } $dominos->@* );
    return sum( grep $_ > 1, values %frequencies );
}

(use v5.36; is short for getting subroutine signatures and automatic strict and warnings.)

I love how Perl makes this easy.

Task 2: Boomerang

You are given an array of points, (x, y).
Write a script to find out if the given points are a boomerang.
A boomerang is a set of three points that are all distinct and not in a straight line.

Example 1
Input: @points = ( [1, 1], [2, 3], [3,2] )
Output: true

Example 2
Input: @points = ( [1, 1], [2, 2], [3, 3] )
Output: false

Example 3
Input: @points = ( [1, 1], [1, 2], [2, 3] )
Output: true

Example 4
Input: @points = ( [1, 1], [1, 2], [1, 3] )

Output: false

Example 5
Input: @points = ( [1, 1], [2, 1], [3, 1] )
Output: false

Example 6
Input: @points = ( [0, 0], [2, 3], [4, 5] )
Output: true

We have the three input points
pi=(xiyi)∣i∈1…3\qquad \qquad p_i = \begin{pmatrix} x_i \\ y_i \end{pmatrix} |_{ i \in { 1 \dots 3 } } pi=(xiyi)i13
My idea to solve this task is based on the two vectors that we get
when we connect these points:
v=(x2−x1y2−y1)w=(x3−x2y3−y2) \qquad \qquad \mathbf{v} = \begin{pmatrix} x_2 - x_1 \\ y_2 - y_1 \end{pmatrix} \qquad \mathbf{w} = \begin{pmatrix} x_3 - x_2 \\ y_3 - y_2 \end{pmatrix} v=(x2x1y2y1)w=(x3x2y3y2)

For a 'boomerang', we then need to check whether the two vectors have the same direction.

The reason why I'm using this 'vector' approach is that I hope to avoid any condition checking that would be necessary for the other possible approach: comparing the slope of the line segments defined by the points. As the points can have the same xxx -coordinate (like in Example 4), I would have to deal with possibly infinite slopes (vertical lines). And in any case with floating point numbers, which I always try to avoid if possible.
Maybe my worries are exaggerated, but I also found it nice to get a little refresher in vector geometry!

So going with the two vectors:
I have re-learned (after around 50 years!) something about the dot product (or scalar product) of vectors.
In the Wikipedia article about the dot product, it says that if two vectors are codirectional, their dot product is equal to the product of their magnitudes.
That sounds complicated, but let's see what that means when we break it down.

The 'dot product' is a scalar number, and for our two vectors
v=(xvyv)w=(xwyw) \qquad \qquad \mathbf{v} = \begin{pmatrix} x_v \\ y_v \end{pmatrix} \qquad \mathbf{w} = \begin{pmatrix} x_w \\ y_w \end{pmatrix} v=(xvyv)w=(xwyw)
it is simply computed like this:
v⋅w=xvxw+yvyw \qquad \qquad \mathbf{v} \cdot \mathbf{w} = x_v x_w + y_v y_w vw=xvxw+yvyw

The 'product of the magnitudes' of the two vectors is
∥v∥ ∥w∥=xv2+yv2⋅xw2+yw2=(xv2+yv2) (xw2+yw2) \qquad \qquad \| \mathbf{v} \| \, \| \mathbf{w} \| = \sqrt{ x_v^2 + y_v^2} \cdot \sqrt{x_w^2 + y_w^2} = \sqrt{ (x_v^2 + y_v^2) \, (x_w^2 + y_w^2)} vw=xv2+yv2xw2+yw2=(xv2+yv2)(xw2+yw2)
The 'magnitude' of a vector is its length, and you recognize the Pythagorean theorem in the two-dimensional case here.

For doing the 'boomerang check', we need to check whether those two are equal:
xvxw+yvyw=(xv2+yv2) (xw2+yw2) \qquad \qquad x_v x_w + y_v y_w = \sqrt{ (x_v^2 + y_v^2) \, (x_w^2 + y_w^2)} xvxw+yvyw=(xv2+yv2)(xw2+yw2)

To avoid floating point operations, and especially something as complicated as computing a square root, we use a trick and square both sides:
(xvxw+yvyw)2=(xv2+yv2) (xw2+yw2) \qquad \qquad ( x_v x_w + y_v y_w ) ^2 = (x_v^2 + y_v^2) \, (x_w^2 + y_w^2) (xvxw+yvyw)2=(xv2+yv2)(xw2+yw2)
Only integer arithmetics, not even a division in this one!

Squaring both sides also has another positive (pun intended!) effect:
If the two vectors have the same direction, but a different orientation
(one is a negative multiple of the other), their dot product is negative. Squaring both sides of the equation eliminates the negative sign, which is what we actually want.

Now we have something that we can turn into code:

use v5.36;

sub boomerang( $points ) {
    # Create vectors connecting the points.
    my $v = [ $points->[1][0] - $points->[0][0],
              $points->[1][1] - $points->[0][1] ];
    my $w = [ $points->[2][0] - $points->[1][0],
              $points->[2][1] - $points->[1][1] ];

    # Compute the dot product
    # and the *square* of the product of the magnitudes
    # (by not taking the square root).
    my $dot_product = $v->[0] * $w->[0] + $v->[1] * $w->[1];
    my $mag_product_squared =
        ( $v->[0] ** 2 + $v->[1] ** 2 )
            * ( $w->[0] ** 2 + $w->[1] ** 2 );

    # Compare the two.
    return $dot_product ** 2 != $mag_product_squared;
}

I added some more tests for corner cases, like two of the three points being identical, or even all three of them.

ok 1 - Example 1: boomerang( [[1, 1], [2, 3], [3, 2]] ) is true
ok 2 - Example 2: boomerang( [[1, 1], [2, 2], [3, 3]] ) is false
ok 3 - Example 3: boomerang( [[1, 1], [1, 2], [2, 3]] ) is true
ok 4 - Example 4: boomerang( [[1, 1], [1, 2], [1, 3]] ) is false
ok 5 - Example 5: boomerang( [[1, 1], [2, 1], [3, 1]] ) is false
ok 6 - Example 6: boomerang( [[0, 0], [2, 3], [4, 5]] ) is true
ok 7 - Extra 1: boomerang( [[1, 1], [2, 1], [1, 1]] ) is false (points 1 and 3 identical)
ok 8 - Extra 2: boomerang( [[1, 1], [1, 1], [2, 1]] ) is false (points 1 and 2 identical)
ok 9 - Extra 3: boomerang( [[1, 1], [2, 1], [2, 1]] ) is false (points 2 and 3 identical)
ok 10 - Extra 4: boomerang( [[1, 1], [1, 1], [1, 1]] ) is false (all points identical)
1..10

Glad all the tests run successfully!

Maybe next time dealing with vectors, I should try PDL!
There's always something new to learn!

Thank you for the challenge!

Find the complete source code for both tasks, including tests, on Github.

utf8n_to_uvchr_msgs: Widen declaration to U16.

Perl commits on GitHub

Published by khwilliamson on Thursday 31 October 2024 18:19

utf8n_to_uvchr_msgs: Widen declaration to U16.

Testing on an EBCDIC box showed that this was too narrow.

isUTF8_CHAR: Remove a conditional from a loop

Perl commits on GitHub

Published by khwilliamson on Thursday 31 October 2024 18:15

isUTF8_CHAR: Remove a conditional from a loop

Instead, this follows the paradigm of
d4e276590cad697e8a374a34d8371921330ec60e.

Known for its agility and simplicity, the Mojolicious framework is especially valued in niche industries with a Perl heritage. In our…

LPW 2024

blogs.perl.org

Published by simbabque on Tuesday 29 October 2024 19:45

I was one of the organisers of the London Perl and Raku Workshop 2024, which happened last weekend. I've written about my own personal experience of this conference over on my personal blog.

London Perl & Raku Workshop 2024: Quick Afterwords

blogs.perl.org

Published by London Perl Workshop on Monday 28 October 2024 18:45

A longer blog post will follow, likely on my personal site (I'll try to avoid it sitting in my drafts folder for too long). In the meantime, thanks to all who attended, spoke, volunteered, helped, advertised, promoted, linked to, encouraged, and so on, this year's London Perl & Raku Workshop. I think it worked out.

scarf.jpeg

Scarves. This year's surprise swag, a 20th anniversary scarf rather than the usual t-shirt. We sill have a few of these left and I'm happy to send you one if you cover the cost of postage and packaging (roughly 15.- CHF). Please email the organisers if you would like one. It wil be first come (emailed) first served. Any that remain I will probably take to GPW next year to give away.

Videos. I will be processing these over the next couple of weeks. Expect them to be available on YouTube sometime mid November.

Feedback. If you attended the workshop it will really help us if you fill in the feedback form. All questions are optional and it is anonymous. Approximately 120 people attended the workshop - if half of you can complete the form that would be smashing.

Next Year? We have no plans. Yet.

Thanks to this year's sponsors, without whom LPW would not have happened:

(dxix) 10 great CPAN modules released last week

Niceperl

Published by Unknown on Sunday 27 October 2024 00: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. DBIx::Connector - Fast, safe DBI connection and transaction management
    • Version: 0.60 on 2024-10-20, with 47 votes
    • Previous CPAN version: 0.56 was 8 years, 7 months, 4 days before
    • Author: ARISTOTLE
  2. Excel::Writer::XLSX - Create a new file in the Excel 2007+ XLSX format.
    • Version: 1.14 on 2024-10-21, with 64 votes
    • Previous CPAN version: 1.13 was 8 days before
    • Author: JMCNAMARA
  3. Future - represent an operation awaiting completion
    • Version: 0.51 on 2024-10-21, with 57 votes
    • Previous CPAN version: 0.50 was 1 year, 7 months, 4 days before
    • Author: PEVANS
  4. Module::CoreList - what modules shipped with versions of perl
    • Version: 5.20241020 on 2024-10-20, with 43 votes
    • Previous CPAN version: 5.20240920 was 1 month before
    • Author: BINGOS
  5. Module::Pluggable - automatically give your module the ability to have plugins
    • Version: 6.2 on 2024-10-25, with 25 votes
    • Previous CPAN version: 5.2 was 9 years, 2 months, 20 days before
    • Author: SIMONW
  6. Perl::Critic - Critique Perl source code for best-practices.
    • Version: 1.156 on 2024-10-23, with 131 votes
    • Previous CPAN version: 1.152 was 1 year, 6 days before
    • Author: PETDANCE
  7. Rose::DB::Object - Extensible, high performance object-relational mapper (ORM).
    • Version: 0.821 on 2024-10-20, with 21 votes
    • Previous CPAN version: 0.820 was 3 years, 3 months, 24 days before
    • Author: JSIRACUSA
  8. SPVM - The SPVM Language
    • Version: 0.990025001 on 2024-10-25, with 33 votes
    • Previous CPAN version: 0.990023 was 7 days before
    • Author: KIMOTO
  9. Text::MultiMarkdown - Convert MultiMarkdown syntax to (X)HTML
    • Version: 1.003 on 2024-10-24, with 13 votes
    • Previous CPAN version: 1.002 was 11 months, 24 days before
    • Author: BRIANDFOY
  10. XML::Compile - Compilation based XML processing
    • Version: 1.64 on 2024-10-21, with 14 votes
    • Previous CPAN version: 1.63 was 5 years, 3 months, 19 days before
    • Author: MARKOV

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

blogs.perl.org

Published by Perl Steering Council on Saturday 26 October 2024 02:07

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.

[P5P posting of this summary]

What Languages Do I Use?

Perl on Medium

Published by Khun Yee Fung, Ph.D. on Sunday 20 October 2024 22:54

I have a simple way to decide whether I will use Ruby, Perl, Java, or Bash. If I need to maintain it 10 years from now. It is in Java. If…

London Perl Workshop 2024 – Preview

Perl Hacks

Published by Dave Cross on Sunday 20 October 2024 15:50

After a break of five years, the London Perl Workshop returns next weekend. It’s been twenty years since the first one. This year’s event is at a new venue called The Trampery, which is very close to Old Street tube station. If you’re a veteran of the early-2000s “Silicon Roundabout” excitement, you’ll know the place as it’s right across the road from The Foundry – the place to be seen if you were working in that area. I seem to remember taking people there as part of the entertainment programme for the first YAPC::Europe back in 2000. The pub isn’t there any more – it’s been knocked down and replaced by a modern hotel.

So I thought I’d have a look at the schedule and point out some of the interesting talks that I’m looking forward to seeing next Saturday.

Following Julian’s introduction, there’s an early indication of the quality of the talks – as there’s a massive clash. I understand how most people would want to see Paul Evans talking about Perl in 2030, but at the same time I’ll be talking about PerlDiver in the other main room. Now, obviously, I don’t want to sway anyone’s decision about which talk to choose – but I will have swag to give away. I don’t have any choice over which room I’ll be in, but I really want to see Paul’s talk, so I’m hoping it’ll be videoed.

I should point out that alongside the two main tracks, there’s a third room that the organisers hope will be used for hackathons, BOFs and things like that.

Next up we have Dave Lambley with ‎Cloudy Perl, how it looks now and Richard Hainsworth with ‎Using new RakuDoc v2. AWS Lambdas and Raku are both things that I’ve never really wrapped my head around. But I suspect that AWS will be more useful to me in the long run, so I’ll be with Dave.

The next choice is between Stuart Mackintosh’s TPRF Presentation and discussion and Ralf Langsdorf who sounds like he’s battling against Little Bobby Tables. I don’t do much community leadership stuff these days, but I’m glad there are still people who are willing to take on those roles – so I’ll be with Stuart. But Ralf’s is another talk that I’ll be looking forward to catching up with later.

In the final slot of the morning, the breakout room is hosting a talk – giving you a choice of three: James Green with ‎I Adopted a Dist, and This is What Happened‎, José Joaquín Atria with Using OpenTelemetry in your Perl libraries and applications‎ and Steve Roe with Raku HTML::Functional‎. I love a good CPAN module story, so I’ll be with James.

There’s then an hour for lunch. I’ll be trying one of the many local sandwich shops or pubs.

First up in the afternoon is a choice between Salve J. Nilsen – Metadata, CPAN, FOSS Supply Chains, and EU’s Cyber Resilience Act‎, Leon Timmermans – ‎A modern introduction to XS‎ and Andrew O’Neil – ‎Chemometrics with Perl & Pharmaceutical Applications. Salve is covering a topic that, while seemingly dull, is something that more people need to take notice of. Leon is covering another topic that I’ve never quite understood. And Andrew is doing science – which is always fun. I think I’ll be listening to Leon in the hope I can finally understand XS.

Next up is Mohammad Anwar explaining ‎What’s new in Perl v5.40?‎, Paul Cochrane on Fixing a fifteen-year-old curve fit bug or Salve is following up on his talk with a CPAN security BOF in the breakout room. Mohammad is always worth watching, but I very much enjoyed reading Paul’s blog post on this bug recently – so I haven’t decided yet where I’ll be.

Then we have a choice between Max Maischein – ‎Managing recent files from Perl‎ (which sounds useful), Nana Insaidoo – ‎opensource vulnerabilities and where to find them‎  (which sounds vital!) and the continuation of Salve’s BOF.

The last slot in this session is Mike Whitaker – Names are hard (which is inarguable), Yujia Zhai – Perl/Raku Based Coursework Design for Engineering Education‎ or even more of Salve’s BOF.

Then we have a twenty-minute break. Phew. I think we’ll all need it after all that top-notch information.

Things get a bit disjointed after the break. There’s Andrew Soloman with ‎Perl Talent Management: How Logicly attracts, develops, and retains their Perl developers. But that overlaps with two talks in the other main room – Ian Boddison with ‎Perl, AI and Your System followed by Saif Ahmed with ‎Bit Vector Arrays to Pixels in a Terminal with One Subroutine. And while all that’s going on, the breakout room has a session of Science Perl Talks‎ chaired by Andrew Neil. They all sound interesting, but my interest in training trumps my other interests, so I’ll be listening to Andrew Soloman.

And then there are the lighting talks. As always, there will be a wide range of talks. I’ll be giving a brief update on Perl School. If you’ve been watching my social media, you might have an idea what I’ll be announcing.

Then we have the intriguingly-named Thanks & The Future of LPW before we all head off to the pub for a debrief.

There are currently about 140 people signed up for the workshop. I don’t know what the venue capacity is, but I’m sure they can squeeze a more in if you’d like to register. Oh, and if you are registered, please mark the talks you’re interested in on the schedule – it makes it easier for the organisers to decide which talks should be in which rooms.

Of course, if you’re not within easy travelling distance of London, then don’t forget that there are other Perl events in other parts of the world. In particular, there will be a TPRC in Greenville, South Carolina next year. See https://tprc.us/ for details.

To close, I’d like to thank the sponsors of this year’s LPW. Without them, the workshop wouldn’t be able to go ahead. Please show them some love.

The post London Perl Workshop 2024 – Preview appeared first on Perl Hacks.

(dxviii) 15 great CPAN modules released last week

Niceperl

Published by Unknown on Saturday 19 October 2024 20:36

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

  1. BerkeleyDB - Perl extension for Berkeley DB version 2, 3, 4, 5 or 6
    • Version: 0.66 on 2024-10-14, with 13 votes
    • Previous CPAN version: 0.65 was 2 years, 5 months, 1 day before
    • Author: PMQS
  2. Catalyst::Plugin::Authentication - Infrastructure plugin for the Catalyst authentication framework.
    • Version: 0.10024 on 2024-10-16, with 12 votes
    • Previous CPAN version: 0.10023 was 11 years, 6 months, 5 days before
    • Author: JJNAPIORK
  3. CryptX - Cryptographic toolkit
    • Version: 0.084 on 2024-10-16, with 51 votes
    • Previous CPAN version: 0.080 was 1 year, 12 days before
    • Author: MIK
  4. DateTime::Format::Flexible - DateTime::Format::Flexible - Flexibly parse strings and turn them into DateTime objects.
    • Version: 0.36 on 2024-10-17, with 14 votes
    • Previous CPAN version: 0.35 was 11 days before
    • Author: THINC
  5. DBD::SQLite - Self Contained SQLite RDBMS in a DBI Driver
    • Version: 1.76 on 2024-10-19, with 104 votes
    • Previous CPAN version: 1.74 was 1 year, 1 month before
    • Author: ISHIGAKI
  6. Dumbbench - More reliable benchmarking with the least amount of thinking
    • Version: 0.505 on 2024-10-15, with 17 votes
    • Previous CPAN version: 0.504 was 3 months, 6 days before
    • Author: BDFOY
  7. Excel::Writer::XLSX - Create a new file in the Excel 2007+ XLSX format.
    • Version: 1.13 on 2024-10-13, with 64 votes
    • Previous CPAN version: 1.12 was 7 months, 16 days before
    • Author: JMCNAMARA
  8. Firefox::Marionette - Automate the Firefox browser with the Marionette protocol
    • Version: 1.61 on 2024-10-18, with 16 votes
    • Previous CPAN version: 1.60 was 2 months, 15 days before
    • Author: DDICK
  9. Hash::Merge::Simple - Recursively merge two or more hashes, simply
    • Version: 0.052 on 2024-10-15, with 17 votes
    • Previous CPAN version: 0.051 was 13 years, 10 months, 8 days before
    • Author: HAARG
  10. meta - meta-programming API
    • Version: 0.012 on 2024-10-14, with 13 votes
    • Previous CPAN version: 0.011 was 6 days before
    • Author: PEVANS
  11. Mojo::JWT - JSON Web Token the Mojo way
    • Version: 1.01 on 2024-10-15, with 17 votes
    • Previous CPAN version: 0.09 was 3 years, 10 months, 23 days before
    • Author: JBERGER
  12. Net::AMQP::RabbitMQ - interact with RabbitMQ over AMQP using librabbitmq
    • Version: 2.40013 on 2024-10-15, with 15 votes
    • Previous CPAN version: 2.40012 was 3 months, 11 days before
    • Author: MSTEMLE
  13. Sub::Util - Common Scalar and List utility subroutines
    • Version: 1.67 on 2024-10-18, with 172 votes
    • Previous CPAN version: 1.66 was 29 days before
    • Author: PEVANS
  14. Scalar::List::Utils - Common Scalar and List utility subroutines
    • Version: 1.68 on 2024-10-18, with 172 votes
    • Previous CPAN version: 1.66 was 29 days before
    • Author: PEVANS
  15. SPVM - The SPVM Language
    • Version: 0.990023 on 2024-10-18, with 33 votes
    • Previous CPAN version: 0.990020 was 7 days before
    • Author: KIMOTO

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

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

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

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.