Repeated Keyboard/Barcode Scanner Console Input

r/perl

Published by /u/nesterbation on Tuesday 12 November 2024 00:42

I'm working on adding a headless front end to a script and I'm trying to get an idea of where to start.

I need to have it continuously looking for input from a handheld barcode scanner. The barcode scanner is, for all intents and purposes, a keyboard. The front end would, upon seeing a scan, fire off a subroutine with that data.

My first thought was curses, but I've never written any perl with a front end, it's always been back side automation, report generation, etc.. So I'm just looking for breadcrumbs/suggestions so I can fall down a rabbit hole of reading and performing random acts of hackery.

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

Image file deleted after display, not before.

I upload a file using Perl's file upload. The upload works fine, it is is the intended upload directory. In the same script, I display the file (it is an image file) and that works ok too. What I want to do is to delete the file after I show it, but when I do that I get a broken link and the image is (of course) deleted from the directory. Tried the sleep function in between to no avail.

print "<img src=\"path_to\image\">
#sleep (5);
unlink "path\to\image\";

I am trying to create a Perl regular expression that will match a person's name. When the name ends with Sr or Jr it is formatted properly with a leading comma and space, and ending with a period.

For example:

Should match:
John Smith
John Smith, Sr.
John Smith, Jr.

Should not match:
John Smith Sr
John Smith, Sr
John Smith, SR.
John Smith Sr.
John Smith, John Smith Sr.
John Smith-

Must also be properly capitalized, i.e. Sr or Jr not sr, SR, sR, jr, JR, or jR. Name should not end with any punctuation, except for a period when Sr or Jr is used.

I tried

^(?!.(Jr|Sr)(?<!,\sJr.)(?<!,\sSr.)$).$

But the above Regex allows for several names that are not acceptable, i.e. John Smith, John Smith Sr.

I then found:

^([A-Za-z]+['-]?[A-Za-z]\s)([A-Za-z]+['-]?[A-Za-z]*)(,\s(Jr|Sr).)?$ 

but it allowed name to end in a hyphen, John Smith-, which should not be acceptable.

Perl Weekly #694 - LPW: Past, Present & Future

dev.to #perl

Published by Gabor Szabo on Monday 11 November 2024 05:32

Originally published at Perl Weekly 694

Hi there,

It has been two weeks since the London Perl and Raku Workshop 2024, and we are still receiving attendee reports. Thank you to everyone who took the time to share their experiences. Last week, I came across two such reports by Lee Johnson and Olaf Alders. I'm still hoping to find a moment to reflect on my own workshop experience.

LPW holds a special place in my heart, as it was the first workshop where I gave my first talk ever. I was introduced to LPW by a colleague at work. Back then, there was always an O'Reilly stall outside the theater room, selling Perl books and surrounded by a large crowd. I remember the days when we had three strong tracks running simultaneously and, especially, the last LPW organized by Mark Keating and his team. The transition was seamless, and we continued the workshop smoothly until COVID-19 struck. For a brief period, I was part of the organizing team, but my contributions were limited to promoting the event and assisting attendees on the day.

Bringing the workshop back after COVID-19 was the brainchild of Lee Johnson and Julien Fiegenhenn. Their hard work truly paid off, as the event was well-attended and praised for its smooth execution. I would like to take this opportunity to thank the organizing team for providing a platform to reconnect with friends from around the world. The future of LPW looks bright as I’m hearing a lot of positive feedback about next year’s workshop, and I'm keeping my fingers crossed.

Enjoy rest of the newsletter.

--
Your editor: Mohammad Sajid Anwar.

Announcements

London Perl & Raku Workshop 2024: Recordings & Thoughts

For all who missed the LPW 2024, we now have the recordings of the event. Audio quality may not be great, I must inform you upfront.

Articles

This week in PSC (167) | 2024-11-07

It seems very busy week, lots of topics discussed amd agreed upon. Happy to see things moving really fast. Thank you Perl Steering Council.

Multiple Inheritance vs Role

A simplified comparison between Multiple Inheritance and Roles.

Further on Perl Camel

The good old discussion of Perl Camel is back ...

Discussion

I wish Mojo::UserAgent could be made to not visit private IPs

An interesting discussion started around the use of Mojo::UserAgent. What is your view on this?

Grants

Dancer2 Documentation Grant Report

Great to see the improvement work being carried out in my favourite web framework, Dancer2.

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

Welcome to a new week with a couple of fun tasks "Word Break" and "Jump Game". 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 - 294

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

TWC294

Rare pairing of 'unless' inside 'foreach' and we have a compact solution, very impressive. Please keep sharing knowledge with us.

Next Consecutive

The verbosity of solutions is the main attraction for me, not just this week but every week. It gives away lots of inner details. Great work, keep it up.

Perl Weekly Challenge: Week 294

Making good use of Raku built-in functions and getting job done in no time. Smart move, well done.

Consecutive Permutations

A very interesting discussion about the use of data structure to get around O(n) time. It's worth checking out, thanks for sharing.

Perl Weekly Challenge 294

Compact one-liner in Perl for all with enough discussion to get to the core. Well done and keep it up.

Consecutive Sequences of Permutations, Anyone?

The detailed analysis to sort out the O(n) time is very impressive. There is always something new to learn from your contributions.

No music, only numbers

Anyone looking for Raku magic then this is the best place where Raku implementation is discussed in details. Having said, I missed the musical aspect.

Sequential permutations

A detailed proof of O(n) time is worth checking. Kudos for the effort, thanks for sharing knowledge with us.

The Weekly Challenge #294

Thanks for sharing the research of finding the lexicographically next permutation. Plenty to learn from this week work.

Permutationally Consecutive

Another dose of Raku gems discussed and it is not to be missed. Highly recommended.

Rakudo

2024.43 One Of 21

Weekly collections

NICEPERL's lists

Great CPAN modules released last week;
MetaCPAN weekly report.

Event reports

Smashed TVs, Broken Windows, and Cracked Plates

Hear from the organiser of LPW what it takes to origanise an event. Kudos for all thier efforts.

How I Spent My First London Perl Workshop

A very colorful presentation, I must admit. Glad that you had great time in London.

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.

Erlang

The Weekly Challenge

Published on Monday 11 November 2024 03:38

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.

YaBasic

The Weekly Challenge

Published on Monday 11 November 2024 03:38

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.

J

The Weekly Challenge

Published on Monday 11 November 2024 03:38

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.

F#

The Weekly Challenge

Published on Monday 11 November 2024 03:38

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.

Miranda

The Weekly Challenge

Published on Monday 11 November 2024 03:38

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.
github CI: the macos-12 runner is deprecated and retires 2024-12-03

https://github.com/actions/runner-images/issues/10721

cpan/Term-Table - Update to version 0.023

Perl commits on GitHub

Published on Monday 11 November 2024 00:34

cpan/Term-Table - Update to version 0.023

0.023     2024-10-26 20:30:20-07:00 America/Los_Angeles

    - t/honor_env_in_non_tty.t requires Test2::Tools::Tiny >= 1.30297;
      use Test::More if not available

perl5411delta.pod - add detail about IsCOW constant-folded strings

Perl commits on GitHub

Published by richardleach on Monday 11 November 2024 00:00

perl5411delta.pod - add detail about IsCOW constant-folded strings

reinstate apostrophe as package separator

Perl commits on GitHub

Published by tonycoz on Sunday 10 November 2024 23:50

reinstate apostrophe as package separator

behind a default enabled feature, which is disabled from feature
bundle 5.41.
perlmod: change the ' deprecation note to mention the feature

Consecutive Sequences of Permutations, Anyone? (PWC 294)

dev.to #perl

Published by Matthias Muth on Sunday 10 November 2024 23:29

Challenge 294 solutions in Perl by Matthias Muth

These are my Challenge 294 Task 1 and 2 solutions in Perl
for The Weekly Challenge - Perl and Raku.

Summary

Task 1: Consecutive Sequences
O(n)O(n) O(n) solution using a small data structure and a lookup hash to keep track of 'streaks' (consecutive sequences) and to merge them with new numbers as they are processed.

Task 2: Next Permutation
Working 'locally' to flip numbers to get the next permutation, without the need to create all permutations first.

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

Task 1: Consecutive Sequence

You are given an unsorted array of integers, @ints.
Write a script to return the length of the longest consecutive elements sequence. Return -1 if none found. The algorithm must runs in O(n) time.

Example 1
Input: @ints = (10, 4, 20, 1, 3, 2)
Output: 4
The longest consecutive sequence (1, 2, 3, 4).
The length of the sequence is 4.

Example 2
Input: @ints = (0, 6, 1, 8, 5, 2, 4, 3, 0, 7)
Output: 9

Example 3
Input: @ints = (10, 30, 20)
Output: -1

Oh. Big Oh. O(n)O(n) O(n) !

This restriction means that the simplest solution, sorting the array and then walking through the ordered numbers, is not allowed. That's because sort has an O(nlog⁡n)O(n \log{} n) O(nlogn) time complexity.

So what we are allowed to do for O(n)O(n) O(n) is to walk through the array. As long as we don't use another loop within a loop, we can even walk through the array several times. This only means that the runtime spent for each number is slightly higher, but this still scales linearly with rising nn n . Actually O(2n)O(2n) O(2n) is the same as O(n)O(n)O(n) .

In fact I do walk through the data twice! I use uniq on the input data, as a first pass (Example 2 contains a 0 twice!). I do this to make sure that double entries do not disturb the detection of sequences.

Let's call a 'consecutive sequence' a 'streak' for short.
We need to build up the 'streaks' as we encounter the numbers, one by one.
The data structure I use for representing a streak is a simple hash:

    $streak = { FROM => $a, TO => $b };

When a new number is encountered, I try to merge that number with any streak that already exists at the number's immediate left or immediate right.

For knowing whether those neighboring streaks already exists , I keep a lookup hash, %streaks. For every streak I create, I put a reference to the streak's data structure into that lookup hash, one with its starting number as the key, and one with its ending number. Thus, to access the left and right neighboring streaks for any new number $n, I only need to check $streaks{ $n - 1 } and $streaks{ $n + 1 }.. And once I have those, I know their 'other ends': the left streak's starting number, and the right streak's ending number. I then can create a new streak that covers them all, the left streak, the new number, and the right streak (if they exist, that is).

What is left to do then is to update the lookup table. I delete any references to the left and right streaks that will not be needed anymore, and I store references to the merged streak in the lookup hash at its starting and ending numbers.

For returning the length of the longest streak in the end, I check whether the new one is longer than what we already have, and update accordingly.

I have left the comments inside the code to make it easier to follow:

use v5.36;
use List::Util qw( uniq );

sub consecutive_sequence_using_hash( @ints ) {
    my $max_streak_length = -1;
    my %streaks;
    for my $n ( uniq @ints ) {
        # Create a new streak from this number,
        # possibly merged with any existing adjacent streaks
        # to the left or to the right.
        my ( $left, $right ) =
            ( $streaks{ $n - 1 }, $streaks{ $n + 1 } );
        my ( $from, $to ) = (
            $left ? $left->{FROM} : $n,
            $right ? $right->{TO} : $n,
        );
        my $streak = { FROM => $from, TO => $to };

        # Update the lookup entries:
        # Remove any entries that are *inside* the merged streak,
        # and add or update entries at the streak borders.
        delete $streaks{ $left->{TO} }
            if $left;
        delete $streaks{ $right->{FROM} }
            if $right;
        $streaks{$from} = $streaks{$to} = $streak;

        # Update the maximum length if this is a streak
        # (not just a single number) and it's longer than what we have.
        $max_streak_length = $to - $from + 1
            if $to > $from && $to - $from + 1 > $max_streak_length;
    }
    return $max_streak_length;
}

No loops inside!
I think this is proper O(n)O(n) O(n) solution.

Task 2: Next Permutation

You are given an array of integers, @ints.
Write a script to find out the next permutation of the given array.
The next permutation of an array of integers is the next lexicographically greater permutation of its integer.

Example 1
Input: @ints = (1, 2, 3)
Output: (1, 3, 2)
Permutations of (1, 2, 3) arranged lexicographically:
(1, 2, 3)
(1, 3, 2)
(2, 1, 3)
(2, 3, 1)
(3, 1, 2)
(3, 2, 1)

Example 2
Input: @ints = (2, 1, 3)
Output: (2, 3, 1)

Example 3
Input: @ints = (3, 1, 2)
Output: (3, 2, 1)

A simple, but compute-intensive solution would be to create all permutations of the numbers involved, then sort them ('lexicographically'), then find the entry that corresponds to the permutation that is given, and then return the next one.
Actually I don't like this approach too much, because in my experience, anything that has to do with permutations or combinations has a tendency to use a lot of time , or a lot of memory, or both, very fast.

Let's find a solution that works 'locally'!

In order to modify an existing permutation to the next higher one, we need to find the number with the lowest significance that can be increased.
That means that we start at the right end (least significant), and find the first number that is lower than its right neighbor. All numbers at the right of that are ordered, highest first, so they can't be 'incremented'.

What if we didn't find any number that is lower than its right neighbor?
In that case, all numbers are ordered, highest first. This must be the last permutation possible. Which means that the next permutation will restart from the beginning of the cycle of all permutations.
In the first permutation, the numbers are ordered lowest first. To get there, we can just reverse that highest permutation sequence of numbers, and we can return that as the result.

If that's not the case, and we do have found a number that can be 'incremented', we need to find the next higher number to replace this number with.
We only look in the right part of the permutation, because using any number from further left would change the order more than we want.
We are looking for the lowest possible number that still is higher than our number.

Once we have found that replacement number, we exchange the two numbers.
We then have 'increased' our number by the next possible higher value of all permutations of the right part. At the same time, we have decreased the replacement number to the next possible lower number. So the ordering of the right part thus still is 'highest to lowest'. As we need the 'first' permutation of the right part, we can just reverse this.

That's it! We have found the lowest possible increment.

Again, I have left the comments in the code for easier following.

use v5.36;

sub next_permutation( @ints ) {
    return @ints
        if @ints <= 1;

    # Starting from the end, find the first number
    # that is lower than the one following it.
    my $index = $#ints;
    while( $index > 0 && $ints[ --$index ] gt $ints[ $index + 1 ] ) {
        # Everything is in the loop condition.
    }

    # No lower number found?
    # Then we are at the end of the permutations.
    return reverse @ints
        if $index == 0;

    my $value = $ints[$index];

    # Find the next highest value within the right part,
    # for using it to replace the current value.
    # (Remember that maybe not all values in the right part are higher!)
    # It has to be higher than the one to substitute, but the
    # lowest possible one.
    my ( $index_2, $replacement ) = ( $index + 1, $ints[ $index + 1 ] );
    for ( $index_2 + 1 .. $#ints ) {
        ( $index_2, $replacement ) = ( $_, $ints[$_] )
            if $value lt $ints[$_] lt $replacement;
    }

    # Swap the two numbers.
    @ints[ $index, $index_2 ] = @ints[ $index_2, $index ];

    # We know that the right side is sorted, highest first.
    # to have it sorted lowest first, we just need to reverse it.
    @ints[ $index + 1 .. $#ints ] =
        reverse @ints[ $index + 1 .. $#ints ];

    return @ints;
}

If we run this several times in a row, we will get a 'consecutive sequence of permutations'.
How nice for the title of this blog, combining the two tasks!

Thank you for the challenge!

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

plenv/perl-build (from Homebrew) have stopped working

r/perl

Published by /u/rjray on Sunday 10 November 2024 21:05

(I'm an experienced Perl person, this is just a weird circumstance.)

I have been using plenv (which uses perl-build) from Homebrew (specifically Linuxbrew) for some time. I had been at Perl 5.38.0 and thought I would try installing 5.40.0 to give it a drive. However, with the tools as installed by brew, I get this:

No backend configured for scheme https at /home/linuxbrew/.linuxbrew/Cellar/perl-build/1.34/libexec/lib/perl5/CPAN/Perl/Releases/MetaCPAN.pm line 48. 

I've googled the hell out of this and tried every solution that's been suggested, including several from previous posts to this sub. None of it has worked. I (foolishly) took one piece of advice about completely blowing away plenv and starting over, and now I don't even have a working 5.38.0. What I currently have is 5.40.0 as installed by brew, but it appears to be missing utf8_heavy.pl, which is preventing a number of modules from installing.

Anyone else run into similar problems? Been trying to get things like B::C built for over an hour, now...

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

I'm trying to build Milvus but encountering a ConanException error related to the missing Digest::SHA module. The error message indicates that it can't locate Digest/SHA.pm in the include paths. Can you please provide guidance on how to resolve this issue?

perl util/mk-fipsmodule-cnf.pl -module providers/fips.so -section_name fips_sect -key f4556650ac31d35461610bac4ed81b1a181b2d8a43ea2854cbae22ca74560813 > providers/fipsmodule.cnf

Can't locate Digest/SHA.pm in @inc (you may need to install the Digest::SHA module) (@inc contains: /usr/local/lib64/perl5/5.32 /usr/local/share/perl5/5.32 /usr/lib64/perl5/vendor_perl /usr/share/perl5/vendor_perl /usr/lib64/perl5 /usr/share/perl5) at util/mk-fipsmodule-cnf.pl line 30.
BEGIN failed--compilation aborted at util/mk-fipsmodule-cnf.pl line 30.

make[1]: *** [Makefile:3341: providers/fipsmodule.cnf] Error 2
make[1]: *** Waiting for unfinished jobs....
ranlib libcrypto.a || echo Never mind.
make[1]: Leaving directory '/root/.conan/data/openssl/3.1.2///build/3639dd31743af9334517609d5baf870330303e60/src'
make: *** [Makefile:2347: build_sw] Error 2

openssl/3.1.2: openssl/3.1.2: ERROR: Package '3639dd31743af9334517609d5baf870330303e60' build failed
openssl/3.1.2: WARN: Build folder /root/.conan/data/openssl/3.1.2///build/3639dd31743af9334517609d5baf870330303e60/build-release
ERROR: openssl/3.1.2: Error in build() method, line 529
self._make()
while calling '_make', line 521
self._run_make()
while calling '_run_make', line 498
self.run(" ".join(command), env="conanbuild")
ConanException: Error 2 while executing make -j64
conan install failed

LPW 2024: Dave Lambley - Cloudy Perl, how it looks now

r/perl

Published by /u/briandfoy on Sunday 10 November 2024 12:31

(dxxi) 9 great CPAN modules released last week

r/perl

Published by /u/niceperl on Saturday 09 November 2024 23:55

(dxxi) 9 great CPAN modules released last week

Niceperl

Published by Unknown on Sunday 10 November 2024 00: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. Catalyst::Runtime - The Catalyst Framework Runtime
    • Version: 5.90132 on 2024-11-08, with 155 votes
    • Previous CPAN version: 5.90131 was 1 year, 3 months, 19 days before
    • Author: JJNAPIORK
  2. DBIx::Class::Helpers - Simplify the common case stuff for DBIx::Class.
    • Version: 2.037000 on 2024-11-08, with 48 votes
    • Previous CPAN version: 2.036000 was 4 years, 7 months, 11 days before
    • Author: WESM
  3. Firefox::Marionette - Automate the Firefox browser with the Marionette protocol
    • Version: 1.62 on 2024-11-03, with 16 votes
    • Previous CPAN version: 1.61 was 16 days before
    • Author: DDICK
  4. Getopt::Long::Descriptive - Getopt::Long, but simpler and more powerful
    • Version: 0.115 on 2024-11-07, with 58 votes
    • Previous CPAN version: 0.114 was 9 months, 18 days before
    • Author: RJBS
  5. Net::DNS - Perl Interface to the Domain Name System
    • Version: 1.48 on 2024-11-08, with 27 votes
    • Previous CPAN version: 1.47 was 1 month, 20 days before
    • Author: NLNETLABS
  6. PDL - Perl Data Language
    • Version: 2.095 on 2024-11-04, with 57 votes
    • Previous CPAN version: 2.094 was 2 days before
    • Author: ETJ
  7. Rex - the friendly automation framework
    • Version: 1.15.0 on 2024-11-05, with 86 votes
    • Previous CPAN version: 1.14.3 was 1 year, 3 months before
    • Author: FERKI
  8. SPVM - The SPVM Language
    • Version: 0.990029 on 2024-11-07, with 33 votes
    • Previous CPAN version: 0.990026 was 6 days before
    • Author: KIMOTO
  9. URI - Uniform Resource Identifiers (absolute and relative)
    • Version: 5.31 on 2024-11-06, with 118 votes
    • Previous CPAN version: 5.29 was 2 months, 1 day before
    • Author: OALDERS

(dxcii) metacpan weekly report - Scalar::List::Utils

Niceperl

Published by Unknown on Sunday 10 November 2024 00:54

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

Week's winners (+4): Scalar::List::Utils 

Build date: 2024/11/09 23:47:36 GMT


Clicked for first time:


Increasing its reputation:

I have this route in my Dancer app: get '/newplayer/:name/:team/:season' => sub { that is called like this: https://website.com/newplayer/Joe Smith/Tigers/Fall 2024 and collects data from the url and put's into a form in the template newplayer.tt so that when the user arrives at the page this information is already mostly filled in.

It works great but I am looking for a way for the route to still be found if there are no values supplied at the url, so that if the user goes to https://website.com/newplayer they still arrive at the page, albeit with an empty form, instead of getting a 404 error. Does anyone know how I can do this?

I found an example of how to embed an arbitrary X application window in a Perl/Tk Notebook widget. However, I am unable to make it work. Specifically, the call to X->ReparentWindow does not work. When called, the xterm application should have moved from displaying in a separate window managed by the window manager to displaying inside the notebook tab in the perl/Tk application.

I've extracted the relevant code into the example below, which assumes a window named xterm is already running. When this runs, the xterm window is not embedded inside the notebook tab. It remains a separate window. I have confirmed that the get_window_by_name function finds the named window via its "class". The use of xterm is just an example. I need to reparent windows from any application.

#!/usr/bin/env perl
use Tk;
use X11::Protocol;
use Tk::NoteBook;
use Data::Dumper;
my $X        = X11::Protocol->new();
my $mw       = MainWindow->new();
my $topframe = $mw->Frame()->pack(-side => 'top');
my $notebook = $topframe->NoteBook()->pack;
my $tab      = $notebook->add("example", -label => "Example");
my $pid;

unless ($pid = fork) { exec("xterm"); }

if ($pid) { sleep(3); grab_it("xterm", $tab); MainLoop(); }

sub grab_it
{
   my $winname = shift;
   my $tab     = shift;
   my $x_window_id;

   $x_window_id = get_window_by_name($winname);
   if (!$x_window_id) { exit(1) }

   $tab->update;
   $X->ReparentWindow($x_window_id, oct($tab->id), 0, 0);
}

sub get_window_by_name
{
   _get_window_by_name($X->{'root'}, $_[0]);
}

sub _get_window_by_name
{
   my ($root, $searchname) = @_;
   my (undef, undef, @new_kids) = $X->QueryTree($root);
   foreach my $k (@new_kids)
   {
      my ($atomnr) = grep { $X->GetAtomName($_) eq "WM_CLASS" } $X->ListProperties($k);
      if (defined $atomnr)
      {
         my ($class, $name) = split(/\0/, ($X->GetProperty($k, $atomnr, "AnyPropertyType", 0, 256, 0))[0]);
         if ($class =~ $searchname)
         {
            return $k;
         }
      }
      my $ret = _get_window_by_name($k, $searchname);
      if (defined $ret)
      {
         return $ret;
      }
   }
   undef;
}

Dancer2 Documentation Grant Report

Perl Foundation News

Published by Saif Ahmed on Friday 08 November 2024 11:36


Jason aka CROMEDOME has submitted a midway report of his Dancer 2 Documentation project. While the project is undoubtedly an important piece of work, his report is also a perfect example of how grants (or indeed any project) should be done. There is a professional demonstration of discipline, identifying goals, challenges, and successes. He has submitted multiple reports through the term, each of which are transparent and reassuring, and I have posted these below.


First Meeting:

  1. Goals and Audience Alignment We started by aligning the grant goals with the proposal, ensuring a clear understanding of the target audience. My primary aim is to improve the documentation quality, making it more accessible and comprehensive for both new and experienced Dancer2 users.

  2. Documentation Review I reviewed the current documentation to identify areas needing updates and improvements. This step helps me focus on specific issues rather than just broad goals. Key areas of focus include:

    • Clarifying core concepts
    • Enhancing examples and tutorials
    • Updating deprecated methods and practices
    • Improving the structure for better readability

We've aligned on these key areas of focus.

  1. Approach and Strategy We discussed the approach for tackling the documentation updates. Specific details include:
    • Using story-driven analogies to explain concepts
    • Implementing task-oriented sections for better usability
    • Ensuring that explanations cater to different levels of user expertise

I will research these ideas to decide what tone and style the documentation will reflect.

  1. Critical Details and Use-Cases We compiled a list of details and specific use cases to cover in the new documentation. These include:

    • Simple "Hello, World!" applications
    • Detailed route handling examples
    • Advanced features like sessions and error handling
    • Real-world scenarios and best practices
  2. Meeting Schedule and Reporting We established a regular meeting schedule to ensure consistent progress tracking. Meetings will be held as follows:

    • Syncing meetings: Once a month with a weekly hold and room for ad-hoc meetings and updates over email
    • Progress reports: First week of every month

This schedule will help us maintain momentum and address any issues promptly.

  1. Immediate Next Steps We outlined the immediate next steps for the documentation work:
    • Determine the tone and style of the documentation
    • Draft introduction and installation sections using the chosen tone and style

Dancer2 Documentation Grant Report for July, 2024

_ Stated Goals_

The goal for month 1 was to work on the core of the Dancer2 documentation, Dancer2::Manual.

Work Accomplished

I spent some time up front talking with my grant manager (Sawyer X) working out a plan of attack and revisiting the planned schedule for the grant. Some things needed to be decided up front: what's the tone of this going to be? How best do we communicate information to users of Dancer2? How do we organize the mess of information that is the current manual in a more coherent way?

A printed manual has multiple chapters/sections to it; larger manuals may span several volumes. I moved any current documentation that clearly is part of the manual to the Dancer2::Manual:: namespace. I then gave each section a clearer purpose (abstract) so someone looking at Dancer2 on MetaCPAN has a better idea of what's in each document. I also revised the documentation map in Dancer2.pm to make clearer what is in each section of the manual.

For a theme, I decided to take a friendly and somewhat humorous approach, which matches the demeanor of most of the Dancer Core Team.

The order of sections in Dancer2::Manual is being reorganized so concepts presented in the manual build on those previously introduced. Each section explains a new concept and what it is used for, shows a commented example of that concept, then explains the why behind that example - why is it necessary, and why is it done that way.

Core concepts in Dancer2 have been explained in the new manual, and a rewritten approach to routes and route handlers is mostly complete.

Up Next

Continued work on the core of the manual. With the first section close to completion, a jump on other sections, and the new format for the layout close to completion, I should be able to focus on producing content for the month of August.

Dancer2 Documentation Grant Report for August 2024

Stated Goals

The goal for month 2 was to work on the core of the Dancer2 documentation, Dancer2::Manual.

Work Accomplished

The reorganization of content in the manual itself (along with the deployment guide) is complete. Work on content continued into templates and sessions, and some advanced content at the end of the manual has been completed.

I worked with my grant manager, Sawyer, to come up with a set of benchmarks to help us determine what done looks like. This will help me to better identify where effort is still needed, and when I can stop working on other sections.

I’m about 2-2.5 weeks behind where I wanted to be at this point. In the grant application, I asked for half a payment at the halfway point, and the remainder upon completion. I feel I need to complete the month 2 goals in their entirety before I should ask, so we will revisit this topic in the September report (I’ll send in early October).

Up Next

Immediate goals consist of catching up on where I want to be in the core manual. After that, I plan to tackle the Deployment Guide and other anscilary documentation.

Dancer2 Documentation Grant Report for October 2024

Stated Goals

Month 3: Example application; review and edit Dancer2::Manual Month 4: Update and revise the cookbook, deployment, and migration guides; final edits

Work Accomplished

Unexpected personal commitments and a recent hurricane impacting my area have led to delays, and the work is now approximately two months behind schedule. Despite these challenges, I have made solid progress and am actively resolving each area as I move forward.

The Manual is essentially complete, pending final reviews before it can be considered finished. Additionally, a new section, Dancer2::Manual::Extending, has been added. This guide covers extension topics, a logical addition that emerged as I wrapped up work on the core manual. The benefit is added readability for users and not having an overwhelming Manual. It is also complete but pending review before it's considered finished.

The cookbook is currently under review, and work is ongoing to define the structure and content of the tutorial. Dancer has a history of difficulties with the Tutorial and we decided to scope it well before I begin the work on it, to maintain clarity for users and focus for my work.

Up Next

After reviewing the remaining work with Sawyer last week, we’ve made adjustments to the schedule. The tutorial, which we expect to be a substantial piece, will be completed at the end to ensure it receives the appropriate focus. We’ve prioritized other items to facilitate timely completion of all areas. The remaining tasks are as follows:

  • Finalize the Cookbook (expected to complete quickly)
  • Review and revise the Deployment Guide
  • Review and revise the Keyword Guide (expected to complete quickly)
  • Publish the above for public review
  • Write the tutorial
  • Process feedback from public review and incorporate relevant changes

You can follow ongoing progress at https://github.com/PerlDancer/Dancer2/tree/docs/doc-rewrite-grant

This week in PSC (167) | 2024-11-07

blogs.perl.org

Published by Perl Steering Council on Friday 08 November 2024 06:07

The three of us attended another long meeting:

  • We continued refining our plan for TLS in core. We will collect feedback on its feasibility from the maintainers of the relevant modules.
  • We reviewed the status of putting the apostrophe package separator behind a feature and approved the PR.
  • We confirmed that we want to deprecate smartmatch with a feature. This effectively means that we don’t plan for a “better smartmatch” at this time (but it can still be pursued in future, by way of the air gap strategy, if there is appetite). We will file an issue for this.
  • We agreed that “negative” features (rather than outright removal) is our preferred way to deprecate historical Perl quirks as the language continues to evolve.
  • We discussed our ongoing inadequacy at dealing with maintenance releases. We wrote down next steps to get back on track, and also started looking into capturing a checklist to document the process.

[P5P posting of this summary]

Multiple Inheritance vs Role

blogs.perl.org

Published by Mohammad Sajid Anwar on Thursday 07 November 2024 21:44

I wish Mojo::UserAgent could be made to not visit private IPs

blogs.perl.org

Published by karjala on Thursday 07 November 2024 16:06

Someone wanting to make a social media site (such as a Mastodon server & web client for example) will want to allow its users to post URLs, for which previews will be shown in their posts.

These posts will be visited by a UserAgent, but there is the risk that a private IP (disguised as a FQDN hostname that resolves to it) will be in the URL's host, and that might cause security issues.

I could use LWP::ParanoidAgent, but then I'd have to fork a process to make the whole thing async, like a good Mojolicious site will be, and too many processes running can be a problem. Also I'd be missing on the many Roles that exist for Mojo::Useragent.

So I opened this issue on Mojolicious's github wishing for a solution.

London Perl & Raku Workshop 2024: Recordings & Thoughts

blogs.perl.org

Published by London Perl Workshop on Thursday 07 November 2024 13:02

Recordings of all talks from this year's London Perl & Raku Workshop are now available on YouTube: https://www.youtube.com/playlist?list=PLxNdCz2kBhVlzbVFcjwY6GkQf4zBhvwFn.

The sound quality of the recordings is not fantastic. We had some sort of issue that I've tried to fix in post. However, the auto generated captions by YouTube tend to be pretty good these days, so enable those if you have any problems understanding the speaker.

I go into the details a bit more about this in a personal blog post about the event, and how much effort is involved in trying to create the recordings, amongst other things.

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

Further on Perl Camel

dev.to #perl

Published by Tib on Thursday 07 November 2024 09:07

Get enough of Perl logo discussion?

You would well take a little bit more! 😉

Get some more
(Picture from Askar Abayev)

I know some people think it's not worth the pain discussing again, but I suppose it's because they don't have the same needs than me and some others 😀

What if you want to use a logo to illustrate a Perl blog? What if you want to use an icon to illustrate Perl sources files (Ubuntu)? What if...?
You either have to use a random camel or ignore the law...

And it's in Perl roots and inside us to be good at free software.

If you don't know well the context, please go read my post The complex topic of Perl logos

Later, I posted my Open Letter To Tim O'Reilly To Free The Perl Camel on Hacker News and people mentioned about the fact that Perl Camel was a "trademark" of O'Reilly, not a copyright (license).

It is true and it's a fundamental thing to understand.

What's the difference between trademark and copyright

Image description
Trademark vs Patent vs Copyright

How is trademarked Perl Camel?

First, just having used the Perl Camel on a book provided to O'Reilly Media a "public statement", then quickly after (in 1998) they secured the trademark via registering trademarks against organisms like United States Patent and Trademark Office (USPTO).

Public statement?

Once a business begins to use a logo to advertise and sell goods or services, they automatically attain common law ownership and the limited protections associated with it—but only if the business can prove it was the first businesses to use the mark. Common law legal protection for a trademark only applies to the geographic area where the business operates. If nationwide protection is needed, then registering a logo with the USPTO is a wise step.

USPTO / WIPO

United States Patent and Trademark Office (USPTO) and World Intellectual Property Organization (WIPO) are organisms where one can register a trademark.

Trademarks are not "global", they apply only in jurisdictions (countries) who recognize it.

We can find USPTO registrations for Perl Camel, I was not able to find one in WIPO (is there any?).

The actual trademark and service mark

"The bottom line is that a trademark represents a product produced by a business (in this case: The Programming Perl book) while a service mark represents a service offered by the business (in this case: O'Reilly selling books). A single business can register both trademarks and service marks to brand themselves."

Trademark

Serial: 75414570
Reg number: 2262465
2nd renewal: 20190828

Perl Camel USPTO Trademark

Camels, both bactrian and dromedary, including heads and other parts uniquely identifiable with camels, and also including stylized, costumed, and those with human attributes

Service Mark

Serial number: 75414568
Reg number: 2209120
2nd renewal: 20181012

Perl Camel USPTO Service Mark

You can search and verify by yourself at USPTO Trademark Search System

Trade dress

More in general, covers of animals (camels but also others) on O'Reilly books seem protected under a Trade dress:

"Trade dress is the characteristics of the visual appearance of a product or its packaging (or even the design of a building) that signify the source of the product to consumers. Trade dress is an aspect of trademark law, which is a form of intellectual property protection law.

In the United States, the Lanham Act protects trade dress if it serves the same source-identifying function as a trademark. It is possible to register trade dress as a trademark, but for practical reasons most trade dress and product configurations are protected without registration."

If copyrights have a duration, how long lasts a trademark?

10 years but you can renew (O'Reilly well renews them when needed).

What is the copyright (license) of O'Reilly Perl camel?

Actually, the design was free when O'Reilly decided to use it.

O'Reilly animal designs are copyright free (public domain). It implies it has no restriction and no license.

Edie Freedman and Hanna Dyers designed the Programming Perl cover based on Animals 1,419 Copyright Free Illustrations of Mammals, Birds, Fish, Insects, etc. by Jim Harter

Animals

So it's important to understand that Perl Camel is not protected because of any copyright/license or creator but because of its association with O'Reilly and books publishing.

Using Perl shadow camel?

Yes, what about this guy?

Perl Shadow Camel

Being a derivative of the Perl Camel does not free us from the trademark. Like using Coca Cola logo just replacing with a "Koka Cola" or changing color from red to blue. No derivative can help, design should not recall in any way the initial trademark/picture and, moreover, the association.

Fair use

The concept of fair use refers to some usages of trademarked logo for some limited usage like representing the brand. For instance, using the Perl Camel to write a blog post about the Perl Camel Book or O'Reilly in general is OK.

Fair use is not well recognized everywhere though.

Blanket license

It exists some solutions to delegate permissions, in the sort of "automatic grant of permissions to use". Somewhat like a blanket license. What was done with The Perl Foundation looks like a bit to a blanket license, but with restrictions. The way it was done makes it still very far from making it "free to use".

Expanding blanket license (remove restrictions and do not attach to TPF) is difficult or impossible without an entity (Perl "community" is not what we can call "an entity").

Logo vs mascot

Using camels to represent Perl has become more like a mascot.

My hypothesis and conclusion

I'm not a lawyer 😉

When we talk about trademarks, we don't talk about something really rigorous. For instance it works on some countries, but not all.
When defending a trademark in court, it's not all black and white, it's more like you build a defense with a maximum of documents and history facts to prove your precedence and that you undoubtly own the trademark (and trade dress).

My hypothesis is that O'Reilly never trademarked other animals with books in his entirety but Perl Camel was the first one (to be trademarked, not the first published). Protecting books covers with animals seems to fall under a "Trade dress" protection, built on top of the Perl camel trademark registration (among maybe other registrations). It means Perl Camel trademark can now be used to protect all others. Sadly for us, it is probably then the cornerstone of the whole protection of "O'Reilly Trademark family" (or more appropriately: "menagerie").

It's why if we dream to have it free, we can't reasonably expect to see it happen. And even if O’Reilly would loose total interest in Perl, it would weaken too much their whole family of books.... And they still remain friends that we don't want to hurt too much.

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.

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

(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

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.

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

(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

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