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.
Published by Photon on Tuesday 29 October 2024 18:50
I get a crash in a situation where I'm trying to iterate over an empty array in a Perl script. The output is
Can't use an undefined value as an ARRAY reference at ...
The array is created by a module and I need to get a stacktrace to help find the root of the problem in this module.
However, when running the script with GDB and trying to get a backtrace, I get a "No stack." message. Indeed, after the "undefined value" error, there are some more lines in the script's output, so it seems like the script doesn't completely crash at this point and thus GDB tries to get its backtrace too late. But the script exits a little bit later (which it wouldn't, if the array had been well defined, so in the long run the error leads to a crash). I'm sorry for the fuzzy problem description, but the code is quite complex (for me) and I'm not sure what is actually happening there... Thus, I'm actually only interested in the following question:
Is there a way to enforce a fatal crash at a given position such that GDB will pick it up and generate a backtrace? Kind of tell GDB: "Here's the problematic variable, please show me a backtrace that lead to it"?
edit: Here is a backtrace including C library information, which I could get for a different crash:
(gdb) bt
#0 XQueryExtension (dpy=0x0, name=0x7ffff7e18000 "X-Resource",
major_opcode=0x7fffffffc0f4, first_event=0x7fffffffc0f8,
first_error=0x7fffffffc0fc) at ../../src/QuExt.c:48
#1 0x00007ffff53ac097 in XInitExtension (dpy=dpy@entry=0x0,
name=name@entry=0x7ffff7e18000 "X-Resource") at ../../src/InitExt.c:59
#2 0x00007ffff5205840 in XextAddDisplay (
extinfo=0x7ffff7e1a110 <_xres_ext_info_data>, dpy=dpy@entry=0x0,
ext_name=ext_name@entry=0x7ffff7e18000 "X-Resource",
hooks=hooks@entry=0x7ffff7e1a0a0 <xres_extension_hooks>,
nevents=nevents@entry=0, data=data@entry=0x0) at ../../src/extutil.c:110
#3 0x00007ffff7e163c9 in find_display (dpy=0x0)
at /build/libxres-6CIuq8/libxres-1.2.1/src/XRes.c:41
#4 0x00007ffff7e164a6 in XResQueryExtension (dpy=dpy@entry=0x0,
event_base_return=event_base_return@entry=0x7fffffffc1c8,
error_base_return=error_base_return@entry=0x7fffffffc1cc)
at /build/libxres-6CIuq8/libxres-1.2.1/src/XRes.c:52
#5 0x00007ffff5ed01dd in init_xres (self=0x55555a04a370)
at ../libwnck/wnck-handle.c:190
#6 wnck_handle_constructed (object=0x55555a04a370)
at ../libwnck/wnck-handle.c:208
#7 0x00007ffff6dc3bba in g_object_new_internal (class=0x55555a04a240,
params=0x7fffffffc380, n_params=1) at ../../../gobject/gobject.c:2654
#8 0x00007ffff6dc5bc3 in g_object_new_internal (n_params=1,
--Type <RET> for more, q to quit, c to continue without paging--c
params=0x7fffffffc380, class=0x55555a04a240)
at ../../../gobject/gobject.c:2920
#9 g_object_new_valist (object_type=<optimized out>,
first_property_name=<optimized out>,
var_args=var_args@entry=0x7fffffffc650) at ../../../gobject/gobject.c:2942
#10 0x00007ffff6dc5f4f in g_object_new (object_type=<optimized out>,
first_property_name=<optimized out>) at ../../../gobject/gobject.c:2415
#11 0x00007ffff5ebfdfa in _wnck_get_handle () at ../libwnck/util.c:161
#12 wnck_screen_get_default () at ../libwnck/screen.c:562
#13 0x00007ffff7e2fb16 in ffi_call_unix64 () at ../src/x86/unix64.S:104
#14 0x00007ffff7e2c3ef in ffi_call_int (cif=cif@entry=0x7fffffffc950,
fn=<optimized out>, rvalue=<optimized out>, avalue=<optimized out>,
closure=closure@entry=0x0) at ../src/x86/ffi64.c:673
#15 0x00007ffff7e2f0be in ffi_call (cif=cif@entry=0x7fffffffc950,
fn=fn@entry=0x7ffff5ebfdc0 <wnck_screen_get_default>,
rvalue=rvalue@entry=0x7fffffffc930, avalue=<optimized out>)
at ../src/x86/ffi64.c:710
#16 0x00007ffff6bb2c2b in invoke_c_code (info=info@entry=0x55555a046f40,
func_pointer=<optimized out>, sp=sp@entry=0x555558aa19e0, ax=ax@entry=1,
items=items@entry=4, internal_stack_offset=internal_stack_offset@entry=4,
package=<optimized out>, namespace=<optimized out>,
function=<optimized out>, mark=<optimized out>)
at /usr/src/libglib-object-introspection-perl-0.051-1build3/gperl-i11n-invoke-c.c:202
#17 0x00007ffff6bb3aa8 in XS_Glib__Object__Introspection_invoke (
my_perl=<optimized out>, cv=<optimized out>)
at /usr/src/libglib-object-introspection-perl-0.051-1build3/GObjectIntrospection.xs:1018
#18 0x00005555556901da in ?? ()
#19 0x000055555568570e in Perl_runops_standard ()
#20 0x00005555555c48ea in Perl_call_sv ()
#21 0x00007ffff6bb0aea in invoke_perl_code (cif=<optimized out>,
resp=0x7fffffffd120, args=0x7fffffffcf70, userdata=<optimized out>)
at /usr/src/libglib-object-introspection-perl-0.051-1build3/gperl-i11n-invoke-perl.c:169
#22 0x00007ffff7e2f641 in ffi_closure_unix64_inner (cif=<optimized out>,
fun=<optimized out>, user_data=<optimized out>, rvalue=<optimized out>,
reg_args=<optimized out>, argp=0x7fffffffd150 "") at ../src/x86/ffi64.c:899
#23 0x00007ffff7e2fd38 in ffi_closure_unix64 () at ../src/x86/unix64.S:303
#24 0x00007ffff6dd26bd in _g_closure_invoke_va (param_types=0x0,
n_params=<optimized out>, args=0x7fffffffd380, instance=0x55555a02a5f0,
return_value=0x0, closure=0x555557390320)
at ../../../gobject/gclosure.c:897
#25 signal_emit_valist_unlocked (instance=instance@entry=0x55555a02a5f0,
signal_id=signal_id@entry=239, detail=detail@entry=0,
var_args=var_args@entry=0x7fffffffd380) at ../../../gobject/gsignal.c:3424
#26 0x00007ffff6dd27c1 in g_signal_emit_valist (instance=0x55555a02a5f0,
signal_id=239, detail=0, var_args=var_args@entry=0x7fffffffd380)
at ../../../gobject/gsignal.c:3263
#27 0x00007ffff6dd2883 in g_signal_emit (
instance=instance@entry=0x55555a02a5f0, signal_id=<optimized out>,
detail=detail@entry=0) at ../../../gobject/gsignal.c:3583
#28 0x00007ffff6a01f2e in g_application_register (
application=application@entry=0x55555a02a5f0,
cancellable=cancellable@entry=0x0, error=error@entry=0x7fffffffd520)
at ../../../gio/gapplication.c:2352
#29 0x00007ffff6a024d0 in g_application_real_local_command_line (
application=0x55555a02a5f0, arguments=0x7fffffffd578,
exit_status=0x7fffffffd574) at ../../../gio/gapplication.c:1155
#30 0x00007ffff6a02823 in g_application_run (application=0x55555a02a5f0,
argc=<optimized out>, argv=0x0) at ../../../gio/gapplication.c:2681
#31 0x00007ffff7e2fb16 in ffi_call_unix64 () at ../src/x86/unix64.S:104
#32 0x00007ffff7e2c3ef in ffi_call_int (cif=cif@entry=0x7fffffffd7e0,
fn=<optimized out>, rvalue=<optimized out>, avalue=<optimized out>,
closure=closure@entry=0x0) at ../src/x86/ffi64.c:673
#33 0x00007ffff7e2f0be in ffi_call (cif=cif@entry=0x7fffffffd7e0,
fn=fn@entry=0x7ffff6a02720 <g_application_run>,
rvalue=rvalue@entry=0x7fffffffd7c0, avalue=<optimized out>)
at ../src/x86/ffi64.c:710
#34 0x00007ffff6bb2c2b in invoke_c_code (info=info@entry=0x555559f86a90,
func_pointer=<optimized out>, sp=sp@entry=0x555558aa19e0, ax=ax@entry=1,
items=items@entry=5, internal_stack_offset=internal_stack_offset@entry=4,
package=<optimized out>, namespace=<optimized out>,
function=<optimized out>, mark=<optimized out>)
at /usr/src/libglib-object-introspection-perl-0.051-1build3/gperl-i11n-invoke-c.c:202
#35 0x00007ffff6bb3aa8 in XS_Glib__Object__Introspection_invoke (
my_perl=<optimized out>, cv=<optimized out>)
at /usr/src/libglib-object-introspection-perl-0.051-1build3/GObjectIntrospection.xs:1018
#36 0x00005555556901da in ?? ()
#37 0x000055555568570e in Perl_runops_standard ()
#38 0x00005555555c3cfd in perl_run ()
#39 0x000055555559963a in main ()
Published by /u/davorg on Tuesday 29 October 2024 15:12
submitted by /u/davorg [link] [comments] |
Published by Tib on Tuesday 29 October 2024 14:38
Few days ago, I participated to London Perl And Raku Workshop and I was shocked and thrilled to see how it was a brilliant success!
For once, I will say a word about Deriv which was the biggest sponsor of the event.
It's a nice place to work 👍 for both juniors and gray hairs (that are very much desired). There's an office in Reading!
Also for once, I will post a picture of me.
The venue was great. Both the location, size and equipment.
When arriving, you got a sticker to wear with your name (great idea!) and a gorgeous scarf (best goodie ever!).
The venue was literally crowded of Perl developers. With a ratio of 2/3 Britishers and 1/3 of foreigners.
It started with a keynote from Julien:
I attended the very much awaited talk from Paul Evans, on Perl syntax, CPAN experiments and Perl future:
In front of this talk was the another very much awaited talk "Perl Diver" that I had to miss (but I managed to steal a picture from it).
Then it continued with a Raku talk ("RakuDoc v2").
I liked this talk.
Then the usual "TPF updates" with half of presentation and half of questions.
One a side (TPF) note, Makoto Nozaki took a recent great initiative with a 3 parts blog posts, doing a big gift to the foundation and everyone, be sure to read them:
This transparency is needed for solid trust in our foundation. It's very much welcome and breaks some relative opacity (not on purpose) of the foundation. So once again thank you Makoto!
Then, a talk that I would never miss, OpenTelemetry from José Joaquín (JJ) Atria. Never deceived by a talk from JJ Atria!
The picture does not render it, but small room was so full that organizers had to refuse people to enter (but by luck I arrived earlier).
And it was already half of the day track...
Went at hotel for lunch and talk preparations. My talk rehearsals took longer than expected and I missed first talks of the afternoon 😢 and also missed the CPAN Security BoF 😢 that was in parallel.
Still was able to attend a later talk about security (Meterian)
And take a moment in a room to work closer with Sebastien, Olaf And Leo (in the common space).
And finally we reached the lightning talks, maybe the activity that I enjoy the most in conferences. I delivered a little talk ("This is a camel") and listened to others (Paul about sdview, Tux about DBI, Dave about Perl School etc...)
Also, Theo Van Hoesel did a tribute to Abe Timmerman, it was very poignant when the whole room did a minute of silence.
The conference ended with a keynote from Lee Jo, revealing the undercover of such event organization.
The venue location was nice.
I walked around it, first reaching Bunhill Fiels cemetery where I relaxed for a while. The place, even being a cemetery, is more like a little garden, and it reigns a absolute calm, it's very pleasant.
William Blake has its tomb here.
I went to the south to reach Saint Paul's Church. My first impression was that it is gigantic (and beautiful).
Another very beautiful place is Guildhall library.
Totally by luck, I discovered a Banksy fresque (the "Banksy Basquiat") in Golden Lane, when going back to hotel after pub on Friday!
Before the event, we enjoyed a beer at Craft Beer (45 min from venue, just good for me). A typical pub with a large choice of beers.
After the event, I even more enjoyed the event at "The Eagle" pub (more people and hello 👋 Stig, Rolf, Salve, Robert...)
It's not a surprise but in UK, as a French guy, and more of that from South of France, I have an accent problem.
It means people don't catch some of my words, even some simplistic ones like "London", "City Road" or "Burden". And worst, my nickname "tib".
Second, it means that my comprehension is very reduced because of British accent (and native using more vocabulary).
First UK is not anymore in EU, so the need of passport.
Second, UK is geographically aligned to where I live, but not aligned as a timezone.
Third, of course I forgot about the different power supply format and had to buy an adapter.
London, at least the area where I stayed, was full of good energy.
You really feel the "go to pub for a beer" cultural habit (when we do "apero" in France), and my hotel had installed a fixed beer bottle opener on a wall.
Do you like me read "Error Count"?
Too long time spent as a programmer...
I finally found where we can buy Red Fedora Hats!
A very picturesque free library
Is it where Perl Monks gathers at end of day?
Going to such even was such a lot of fun, socializing and charging battery that I'm more than grateful to have been part of it. I really feel like "privileged".
Again, it was a a brilliant success, thanks to organizers, speakers, attendees and all.
See you again and "Long live to Perl!"
Published by khwilliamson on Tuesday 29 October 2024 13:52
Remove unused internal function bytes_from_utf8_loc Commit e4d3d0c06a98ce383c7fd3ab553a4ae1c2226cf9 removed all the calls to this function.
Published by tonycoz on Tuesday 29 October 2024 04:46
cygwin: workaround DLL load address conflict The DLL load addresses are generated by the linker based on the DLL names, and 5.39.10 we're getting a conflict between cygperl5_41_6.dll and Langinfo.dll. As a workaround, statically link Langinfo into cygperl for CI and mention the problem in perldelta for anyone else who might build perl on cygwin Fixes but should not close #22695
Published by khwilliamson on Monday 28 October 2024 20:38
perlapi: Fix missing entry
Published by khwilliamson on Monday 28 October 2024 20:38
XS-APItest/t/utf8.t: Tidy Clarify comment and note() and vertically align a table
Published by /u/jjatria on Monday 28 October 2024 20:35
submitted by /u/jjatria [link] [comments] |
Hey Gang,
There's a small CPAN module I've been wanting to make use of, but it neither passes its tests nor installs. There's also poorly defined metadata (in particular, dependencies). I forked the GitHub repo and submitted a PR with fixes as a dzil distribution on September 11, but the Hong Kong-based author is non-responsive. I've just emailed them to prompt a merge or hand-off.
What are my next steps if I hear nothing back and I want to adopt the package?
Thanks,
Iain.
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.
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:
Published by khwilliamson on Monday 28 October 2024 15:55
Remove mathoms stub Perl_gv_SVadd()
Does anybody have an idea how to do it? The Perl debug adapter extension is not clear about what and how it is doing it. Clicking 'debug' or 'run' starts the debug session, stops on entry and dies after a few seconds (it runs the script to completion).
The Perl debug adapter recommends bscan's Perl Navigator (which I use) in tandem, but it doesn't say in what way it is connected to it. Moreover, it has no settings.
How to create a launch.json for just a single script??
"configurations": [ { "type": "perl", "request": "launch", "name": "Perl Debug", "program": "${workspaceFolder}/${relativeFile}" <---I DON"T NEED THIS. WHat to place instead???, "stopOnEntry": true }
Published by Gabor Szabo on Monday 28 October 2024 04:59
Originally published at Perl Weekly 692
Hi there,
The London Perl and Raku Conference 2024 finally happened last Saturday 26th October. It was a pleasant morning to start the day. I happened to arrive a bit early at the venue and met Paul Evans as he was going through the slides of his upcoming talks. It was nice to have a one-on-one conversation with him. For the first time in many years of attending LPW, I finally mustered the courage to break the ice.
Soon we all gathered in the main hall for the welcome presentation by Julien. I stayed in the same room for the most anticipated talk, Perl in 2030 by Paul Evans. As expected it was an engaging presentation about the future of Perl. This was followed by another interesting talk, Cloudy Perl, how it looks now by Dave Lambley. We took a break from technical talks for a quick presentation by Stuart Mackintosh who shared how TPRF is working towards the development of Perl and Raku. I had the honour of speaking to him afterward, thanking him for all the work TPRF is doing to bring the language back on track.
Unfortunately I missed the talk, Perl Diver by Dave Cross as it clashed with Paul Evans presentation. I am hoping to watch the video when it becomes available. I met so many friends after a long time, thanks to LPW 2024. I missed Neil Bowers and Lance Wicks very much but I was pleasantly surprised to meet Sawyer, Olaf Alders and Paul Cochrane. We spent quality time together.
After lunch, it was my turn present, What's new in Perl v5.40?. It was well attended, and Paul Evans made it even more special by sitting in the front row. I mostly stayed in the main hall for the rest of the talks and look forward to the recordings being available soon.
I had planned to attend the post workshop social but decided to skip it at the last minute as I wasn't feeling well. I am sure those who attended had a great time. I hope to see you all again around this time next year.
Last but not least I would like to encourage you to submit your proposal for the Perl Advent Calendar 2024. You can find more information here.
Enjoy rest of the newsletter and please take extra care of yourself.
--
Your editor: Mohammad Sajid Anwar.
It was all about working on document about Perl version. Curious to know more about it.
If you missed the talks by Dave then this is for you. It is worth bookmarking for later reading.
Please find the slides of my talk at LPW 2024. I hope you find it useful.
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.
Welcome to a new week with a couple of fun tasks "Similar Dominos" and "Boomerang". 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.
Enjoy a quick recap of last week's contributions by Team PWC dealing with the "Twice Largest" and "Zuma Game" tasks in Perl and Raku. You will find plenty of solutions to keep you busy.
For all Raku fans, this is your chance to learn some more Raku magics. Highly recommended.
A very brave approach to solve the Zuma Game task using regex. The detailed discussion is really handy. Great work, keep it up.
Raku never misses the opportunity to surprise me. Yet another gem from Laurent, brilliant work. Thanks for sharing knowledge with us every week.
Master of Perl one-liners didn't disappoint us this week as always. This is not to be missed for all Perl fans. Great work.
Not just one but two different approaches discussed this week. It is very engaging for me. You must checkout too.
For music fans, we have powerful solutions with musical background. It is so much going through the technical details. Cool, keep it up.
Breaking down big task into smaller sub tasks can be very handy. With DIY tool, you get to play with it too. Great work, thanks for sharing.
Simple yet effective algorithm gets you the desired result. It is self explanatory. Thanks for the contribution.
Nicely modularised solutions with enough documentation to get you to the bottom on task. Keep sharing the knowledge.
Rust seems the favourite programming language as it is the choosen one to solve the Zuma Game task. I must admit, you would need patience to follow through. Highly recommended.
Great CPAN modules released last week.
November 12, 2024, Virtual event
November 13, 2024, Virtual event
November 28, 2024, Virtual event
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.
Published on Monday 28 October 2024 04:05
Published by Unknown on Sunday 27 October 2024 00:06
Published by Gavin Baumanis on Saturday 26 October 2024 21:39
I am trying to work out a Perl regex for adding in a space around equals sign ("=") - but only if there isn't a space there already:
var myVariable="thisValue" -> var myVariable = "thisValue"
var mySecondVariable ="thisValue" -> var mySecondVariable = "thisValue"
var myThirdVariable= "thisValue" -> var myThirdVariable = "thisValue"
I have managed to replace valid characters with a space.
I have managed to have double-spaces before a "="... and nothing after.
Published by anshu kumar on Saturday 26 October 2024 05:04
While installing Module::pluggable, its failing during test. Command using to install:
cpanm --mirror https://artifactory.factset.com/artifactory/cpan.org/ Module::Pluggable
LOG:
t/29unreadable.t ............. 1/6
# Failed test at t/29unreadable.t line 31.
# Structures begin differing at:
# $got->[0] = 'Unreadable::Foo'
# $expected->[0] = Does not exist
# Failed test at t/29unreadable.t line 36.
# Structures begin differing at:
# $got->[0] = 'Unreadable::Foo'
# $expected->[0] = Does not exist
# Looks like you failed 2 tests of 6.
t/29unreadable.t ............. Dubious, test returned 2 (wstat 512, 0x200)
Failed 2/6 subtests
Test Summary Report
-------------------
t/29unreadable.t (Wstat: 512 Tests: 6 Failed: 2)
Failed tests: 2, 4
Non-zero exit status: 2
Is there any change? We can use force but not sure why it's failing. I have perl version: 5.16.0.
When used force it skipped the test and installation is successful. I am also trying to install datetime module which is somehow dependent on Module::Pluggable
Published by Perl Steering Council on Saturday 26 October 2024 02:07
This week, we talked about some recent (and less recent) p5p threads:
Published by Perl Steering Council on Saturday 26 October 2024 02:05
This week’s meeting was delayed by scheduling conflicts because we chose consistency and availability over partition tolerance. We spent the entire meeting working on the document we wanted to put together a month ago with our thoughts on the Perl version number, which we intend to publish very soon.
Published by user4035 on Friday 25 October 2024 13:40
Here is the code that tries to output text in koi8-r single-byte encoding to the browser. I saved it in Emacs in koi8-r:
#!/usr/bin/perl
use Mojolicious::Lite;
no utf8;
get '/' => sub {
my $c = shift;
$c->res->headers->content_type('text/plain; charset=KOI8-R');
# Respond with plain text
$c->render(text => "Hello, World! Текст на русском однобитный.");
};
app->start;
I works but instead of "Hello, World! Текст на русском однобитный." in Firefox I see:
Hello, World! ц╢ц┘ц▀ц⌠ц■ ц▌ц│ ц▓ц∙ц⌠ц⌠ц▀ц▐ц█ ц▐ц└ц▌ц▐ц┌ц┴ц■ц▌ц≥ц┼.
After I click View - "Repair text encoding", I get:
Hello, World! ôÅËÓÔ ÎÁ ÒÕÓÓËÏÍ ÏÄÎÏÂÉÔÎÙÊ.
I seems that "Текст на русском однобитный" is being interpreted in Windows-1252 instead of koi8-r and that's why I see "ôÅËÓÔ ÎÁ ÒÕÓÓËÏÍ ÏÄÎÏÂÉÔÎÙÊ".
What is wrong? Maybe render
function can't work with single byte encoding?
Published by bliako on Thursday 24 October 2024 17:07
I am using Mojolicious (Lite) for a simple app where after login I want to redirect to a named route (already defined in the app) with the additonal requirement that I have a lot of JSON data to pass to it.
This route is also used by other parts of the app, for example, by clicking a button on the html page which ajax'es, via JS, to call this page with the JSON data.
My first thought is to declare this route as POST.
My question is how, after successful login, to move, from inside the Mojolicious app, to that page via a POST, with my JSON data. I have used Controller's redirect_to()
before for GETting to the new page without significant JSON data but what if I have lots of JSON which is cumbersome to pass it on via url-params (e.g. http://example.com?p=mybigjsonencoded
)?
EDIT: I am trying now to use controller's proxy->post_p()
which proxies and gets that page which is then rendered. Isn't this cumbersome too?
Published by laurent_r on Wednesday 23 October 2024 02:32
These are some answers to the Week 292, 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 October 27, 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.
You are given an array of integers, @ints
, where the largest integer is unique.
Write a script to find whether the largest element in the array is at least twice as big as every element in the given array. If it is return the index of the largest element or return -1 otherwise.
Example 1
Input: @ints = (2, 4, 1, 0)
Output: 1
The largest integer is 4.
For every other elements in the given array is at least twice as big.
The index value of 4 is 1.
Example 2
Input: @ints = (1, 2, 3, 4)
Output: -1
The largest integer is 4.
4 is less than twice the value of 3, so we return -1.
My first comment is that we don't really know what to do with negative integers, especially if all input values are negative. We will assume that exactly the same rules apply for negative values (an array with only negative values will always qualify because when you double a negative value, it becomes smaller, not larger), or that the input array will contain only non-negative values.
There is no other solution than to check (even if implicitly, say with a sort
) each number of the input array. The only very slight difficulty is that we should not compare the greatest number in the input array with twice its value, because it would always fail (except if the greatest integer is 0, but that's an edge case).
Once we have integrated the considerations in the previous section (please read them if you didn't), the solution is straight forward. I was initially hoping to use a junction, probably an any
or none
junction, but the fact that we need to exclude the largest item from the comparison makes it slightly more complicated and less efficient (since we would have to visit each input value once more). So, I used a simple loop. Thinking again about it afterward, I came to the conclusion that using a one
junction might have avoided the need for an extra loop: if there is one (and only one) value whose double is larger than the greatest integer, then our input array almost certainly satisfies the task's conditions (at least with positive input values). Testing that alternate solution is left as an exercise for the reader.
sub twice-larger (@in) {d for an extra loop.
my ($max-i, $largest) = @in.max(:kv);
for @in -> $i {
next if $i == $largest;
return -1 if 2 * $i > $largest;
}
return $max-i;
}
for (2, 4, 1, 0), (1, 2, 3, 4), (4, 3, 5, 12, 2) -> @test {
printf "%-12s => ", "@test[]";
say twice-larger @test;
}
This program displays the following output:
$ raku ./twice-largest.raku
2 4 1 0 => 1
1 2 3 4 => -1
4 3 5 12 2 => 3
This program is essentially a port to Perl of the above Raku program. Please refer to the previous sections if you need explanations. Since Perl doesn't have junctions
, we need to use a loop over the input values, just as we did in Raku. Note that we had to implement a max
auxiliary subroutine, since there is no built-in function to do that (which is no problem, as it is very simple and worked fine straight out of the box).
use strict;
use warnings;
use feature 'say';
sub max {
my $max = shift;
for (@_) {
$max = $_ if $_ > $max;
}
return $max;
}
sub twice_larger {
my $largest = max @_;
my $max_i;
for my $i (0..$#_){
my $val = $_[$i];
if ($val == $largest) {
$max_i = $i;
next;
}
return -1 if 2 * $val > $largest;
}
return $max_i;
}
for my $test ([2, 4, 1, 0], [1, 2, 3, 4], [4, 3, 5, 12, 2]) {
printf "%-12s => ", "@$test";
say twice_larger @$test;
}
This program displays the following output:
$ perl ./twice-largest.pl
2 4 1 0 => 1
1 2 3 4 => -1
4 3 5 12 2 => 3
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 3, 2024. And, please, also spread the word about the Perl Weekly Challenge if you can.
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…
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.
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.
You are given an array of integers, @ints
.
Write a script to find the leftmost middle index (MI) i.e. the smallest amongst all the possible ones.
A middle index is an index where ints[0] + ints[1] + … + ints[MI-1] == ints[MI+1] + ints[MI+2] + … + ints[ints.length-1]
.
This is relatively straight forward. I loop through the position from 0 to one less than the length of the inputs. At each position I see if the condition is met.
def middle_index(ints: list) -> int:
for i in range(len(ints)):
if sum(ints[:i]) == sum(ints[i + 1:]):
# It is, so return this position
return i
return -1
$ ./ch-1.py 2 3 -1 8 4
3
$ ./ch-1.py 1 -1 4
2
$ ./ch-1.py 2 5
-1
A draw poker hand consists of 5 cards, drawn from a pack of 52: no jokers, no wild cards. An ace can rank either high or low.
Write a script to determine the following three things:
Strap in, because this is going to be a long post. It's also the first time in a long time that a task hasn't required any input. In the challenges I've completed, the last one was #177.
To answer the first question, there are 311,875,200 possible permutations of cards that can be dealt (52 × 51 × 50 × 49 × 48). However, the order of cards does not matter. For any five drawn cards, they can be arranged in 120 ways (5 × 4 × 3 × 2 × 1). Therefore there are 2,598,960 unique combinations.
I start by creating a deck of cards. For this I have a rank (card number) of 1 to 13. 1 is an ace, 2 to 10 are the numbers, 11 is Jack, 12 is Queen and the King is 13. I also have a suit s
, c
, d
and h
(spare, club, diamond and heart respectively). Using a double for loop, I generate all 52 cards (a tuple of rank and suit) and store this in a list called deck
.
I then loop through each unique five card combination of deck
, and determine what hand I hold. Finally I print the results.
from collections import Counter, defaultdict
from itertools import combinations
def main():
deck = [(rank, suit) for rank in range(1, 14) for suit in ('s', 'c', 'd', 'h')]
hands = defaultdict(int)
for cards in combinations(deck, 5):
hand = get_hand(cards)
hands[hand] += 1
display_results(hands)
That's the easy part :)
For the get_hands
function, I start by creating a dict of lists sorting by rank (the number on the card) and suit (the symbol on the card). I also count the frequency of ranks, as this is often used to determine the hand.
def get_hand(cards):
cards_by_rank = defaultdict(list)
cards_by_suit = defaultdict(list)
for card in cards:
number, suit = card
cards_by_rank[number].append(card[1])
cards_by_suit[suit].append(card[0])
count_by_rank = Counter(len(cards_by_rank[r]) for r in cards_by_rank)
So for the cards 10s, 10h, 9d, 8h, 2d, the following would be set:
{10: ['s', 'h'], 9: ['d'], 8: ['h'], 2: ['d']}
{'s': [10], 'h': [10, 8], 'd': [9, 2]}
{1: 3, 2: 1}
(there are three ranks that appear once, and one that has two cards)It's then time to determine what hand I am holding. We'll start with the straight flush and flush. These are the only hands that consider the suit of the cards, and that all fives cards are of the same suit. This is determined when the cards_by_suit
dict only has one value.
To determine if it is a straight flush, I order the cards numerically (from 1 to 13). If the first card is 1 (an ace) and the last card is 13 (king), I remove the first card and append 14 to the end of the list. This allows a 10, Jack, Queen, King and Ace to be considered a straight flush. A straight flush occurs when the difference between the first card number and last card is four.
if len(cards_by_suit) == 1:
cards = sorted(cards_by_rank)
if cards[0] == 1 and cards[4] == 13:
cards.pop(0)
cards.append(14)
if cards[4] - cards[0] == 4:
return 'Straight flush'
return 'Flush'
For the four of a kind hand (four of one rank, and a random last card) and full house (three of one rank, two of a different rank), I can use the count_by_rank
dict to see if the hand matches the specified criteria.
if count_by_rank[4]:
return 'Four of a kind'
if count_by_rank[3] and count_by_rank[2]:
return 'Full house'
To determine if the hand is straight, I use a similar logic to the straight flush. I first check that I have five unique ranks (card numbers), order them, move the ace if required, and check if the difference between high and low is 4.
if len(cards_by_rank) == 5:
# Get the card ranks in the possible flush
cards = sorted(cards_by_rank)
if cards[0] == 1 and cards[4] == 13:
cards.pop(0)
cards.append(14)
if cards[4] - cards[0] == 4:
return 'Straight'
Three of a kind (three cards of a single rank, two cards of different ranks), two pairs (two cards of one rank, two cards of a different rank, random last card), one pair (two cards of one rank, three cards of a different rank each) can all be calculated using the count_by_rank
dict.
if count_by_rank[3]:
return 'Three of a kind'
if count_by_rank[2] == 2:
return 'Two pair'
if count_by_rank[2]:
return 'One pair'
And finally if nothing matches, return 'High card'. You definitely won't want to bet your house if you are holding this hand :)
return 'High card'
The display_results
function simply displays the results (ordered by rank) in a uniformed layout. As mentioned at the start for each combination there are 120 permutations the card could be ordered in.
def display_results(hands):
hand_names = [
'Straight flush', 'Four of a kind', 'Full house', 'Flush', 'Straight',
'Three of a kind', 'Two pair', 'One pair', 'High card',
]
fmt = '{:16} {:>17,} {:>12,}'
print('Hand Combinations Permutations')
print('------------------- ------------ ------------')
for hand in hand_names:
print(fmt.format(hand, hands[hand], hands[hand] * 120))
print('------------------- ------------ ------------')
print(fmt.format('Total', sum(hands.values()), sum(hands.values()) * 120))
$ ./ch-2.py
Hand Combinations Permutations
------------------- ------------ ------------
Straight flush 40 4,800
Four of a kind 624 74,880
Full house 3,744 449,280
Flush 5,108 612,960
Straight 10,200 1,224,000
Three of a kind 54,912 6,589,440
Two pair 123,552 14,826,240
One pair 1,098,240 131,788,800
High card 1,302,540 156,304,800
------------------- ------------ ------------
Total 2,598,960 311,875,200
This took about 15 seconds to run on my home PC.
As we can see from the bottom row, we have 2,598,960 combinations and 311,875,200 permutations. This matches what we expected to see in the output.
Published by Unknown on Saturday 19 October 2024 20:36
Published by Noman Mohammad on Wednesday 16 October 2024 11:26
Are you new to Linux and wondering how to run a Perl script on your system? If you’re just starting with Linux or Perl, don’t worry…
Published by Paul Cochrane 🇪🇺 on Monday 14 October 2024 22:00
When searching for a subset of rows in a database table by using a list of entries in one of its columns, one can use the WHERE column_name IN list
syntax in an SQL query. How to do this using DBIx::Class
wasn’t obvious to me; at least, not by reading the docs. I worked it out eventually. Here’s what I learned.
This won’t be new to many people, but it was new to me and I couldn’t find the part of the docs where this is discussed, so I thought I’d write it up here for my future self to find.
Imagine this situation: you have a database table from which you want to select a subset of its rows depending upon known values of one of its columns. Take this data for example, which represents possible failure states in an application:
id | name | severity |
---|---|---|
0 | Ok | 0 |
1 | Warning | 1 |
2 | Critical | 2 |
3 | Error | 3 |
4 | Degradation | 1 |
5 | Mismatch | 1 |
6 | Contamination | 2 |
7 | Unknown | -1 |
Now imagine that not all parts of the application use all failure states. Some only need to use Ok
, Warning
, Critical
, and Error
, while others use Ok
, Degradation
, Mismatch
and Unknown
. How does one pull out the rows only of interest to that specific part of the application? One way to do this would be like so (note: I’m still a bit of an SQL noob, so be nice to me):
SELECT * FROM failure_states WHERE name IN ('Ok', 'Degradation', 'Mismatch', 'Unknown');
That’s cool. Now, I’ve been working more with DBIx::Class
recently, having spent the last several years working almost only with Django and its ORM, hence I’m also a DBIx::Class
noob. Anyway, I wanted to do this lookup from DBIx::Class
and only stumbled across the example mentioned in the search
docs for DBIx::Class::ResultSet
, i.e. this bit:
my @cds = $cd_rs->search({ year => 2001 }); # "... WHERE year = 2001"
my $new_rs = $cd_rs->search({ year => 2005 });
my $new_rs = $cd_rs->search([{ year => 2005 }, { year => 2004 }]);
# year = 2005 OR year = 2004
Using this pattern to solve the problem above yields code like this:
my @states = FailureState->search(
[
{ name => 'Ok' },
{ name => 'Degradation' },
{ name => 'Mismatch' },
{ name => 'Unknown' },
]
);
That, as one might say in the New Zealand vernacular, is fugling uckly. Putting things another way, there’s a lot of duplication here, which doesn’t make this solution DRY and it’s not a pattern that would scale well. It works, but surely there’s a better way, right?
It turns out that yes, there is a better way, and as is often the case, I found an appropriate answer on StackOverflow. Also, because this is Perl, there is more than one way to do it. For instance with the =
operator within a search()
method call:
my @state_names = qw(Ok Degradation Mismatch Unknown);
my @states = FailureState->search(
{
name => { '=' => [@state_names] }
}
);
This probably does something like WHERE name = $state_name
in the background … I guess? I’m not sure about the details here, so I’m going to be content with waving my arms as an explanation.
Alternatively, one can use a syntax reminiscent of the WHERE column_name IN list
syntax:
my @state_names = qw(Ok Degradation Mismatch Unknown);
my @states = FailureState->search(
{
name => { -in => [@state_names] }
}
);
But why use several lines when only two are sufficient? One can be more direct and pass an arrayref:
my @state_names = qw(Ok Degradation Mismatch Unknown);
my @states = FailureState->search( { name => \@state_names } );
Nice!
I’m sure there are other and better ways of doing this. Even so, this change has simplified my code nicely. Also, I learned something new today, which was cool :-)
Published by Gabor Szabo on Monday 14 October 2024 06:43
Originally published at Perl Weekly 690
Hi there,
Happy Hacking everyone !!!
I hope you are busy contributing during this year Hacktoberfest. We are half way through already but still plenty of time left to kickstart if not done already.
How about LPW 2024?
Well it is less than 2 weeks before the much awaited London Perl & Raku Workshop 2024 begins the fun. I am very happy to see the support of Perl community in general. It is great to see regular names in the list of sponsors, specially my current employer Oleeo as Gold sponsor. Thank you, Lee Johnson, for all the hardwork, managing the event so smoothly so far. I am confident it would be a memorable event for everyone.
Those who are planning to attend the event, there would be Pre Workshop Social and Post Workshop Social. Please register your details asap. I have once attended pre workshop social in the past as the usual venue is not my favourite spot. Having said, I am planning to break the tradition this year and planning to attend post social workshop. How can I miss the opportunity to meet my techie friends.
Have you seen the favourite talks list?
I am personally looking forward to attend the talks e.g. Perl in 2030, Cloudy Perl, how it looks now, A modern introduction to XS. Also my own talk, What's new in Perl v5.40?. I happy to see the some familiar names shown interest in my talk. I can't wait to present my talk.
I am also looking forward to meet some of my techie friends after a long time. Recently I found out one coming all the way from Canada. I am wondering if anyone coming from Japan. In the past, we always had speaker from Japan. I hope to see the familiar face this time too. Anyone from Germany? We will all find out first thing at the registration desk on the day.
As the October arrived, it also brought the dull weather with it. I don't have good memory about it. I hope it passes without creating any havoc. You take extra care of your health, specially mental and enjoy rest of the newsletter.
--
Your editor: Mohammad Sajid Anwar.
A new module, Weather::ORM just arrived. The OpenWeather API has a Free tier with both current weather and forecast, which makes the module useful to anyone interested in fetching weather for any location.
Olaf Alders joined this week PSC meeting exchanged ideas.
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.
Create a parallel echo server using SPVM::IO::Socket::IP and goroutines, channels, select in SPVM::Go.
Wouldn't you like to output a single executable file from your AI program? Then, you can run the AI program just by copying the executable file to the Raspberry Pi.
This is the beginning of wxPerl revival. Please do support the initiative.
Oleeo is an award-winning provider of innovative talent acquisition technology. Built using intelligent automation and machine learning, Oleeo’s platform helps companies discover unlimited sourcing potential to attract, engage and hire amazing, diverse teams that change the world for the better.
Geekuni can give software developers with no previous Perl experience the training they need, as they need it. Geizhals Preisvergleich is one of the largest product and price comparison platforms in the German-speaking area.
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.
Welcome to a new week with a couple of fun tasks "Middle Index" and "Poker Hand Rankings". If you are new to the weekly challenge then why not join us and have fun every week. For more information, please read the FAQ.
Enjoy a quick recap of last week's contributions by Team PWC dealing with the "Double Exist" and "Luhn's Algorithm" tasks in Perl and Raku. You will find plenty of solutions to keep you busy.
Compact solutions in Perl as always and self explanatory. You really don't want to miss it.
Simple yet elegant approach in Perl and Go. Great work, keep sharing.
Interesting way to deal with edge case using the power of Raku. And on top, get the complete official word on each feature used.
You get nice story to start with and then comes the technical discussion. It is engaging yet, thanks for sharing.
Line-by-line discussion is a cool way to get the end result. Keep it up great work.
As per the tradition, we got side by side implementation in Perl and Raku. Plenty for both fans, keep the tradition alive.
Real life story behind Luhn's algorithm. Thanks for sharing the story with us. Great work.
Simple loop in Raku is enough to get this week task done and self explanatory too. We also have bonus solutions in Java, Python and PostgreSQL.
In-house Perl one-liner expert sharing the quality implementation. Keep it up great work.
Smart use of CPAN to get a compact solution in Perl. Simple love the detailed discussion. Keep sharing the knowledge with us.
Musical background to the weekly challenge is always fun. Following which we get the thorough discussion of implementation in Perl, Raku, Python and Elixir. Highly recommended.
A verbose approach to make it easy to read and follow. DIY tool is the icing on the cake. Well done.
Old school double loops with detailed comments. Keep it up great work.
We got another musical solution. I just love the musical theme. Keep sharing knowledge.
Postscript is one language that I find very fascinating and when we get the detailed narration then it becomes so easy to follow. Highly recommended.
Two in a row, what a pleasant surprise. Thanks for the quality blog post. Please keep sharing.
Like always, the post is dedicated to Python fans. Plenty for Perl fans to learn. Keep it up great work.
Great CPAN modules released last week.
October 24, 2024, Virtual event
October 26, 2024, in London, UK
November 12, 2024, Virtual event
November 13, 2024, Virtual event
You joined the Perl Weekly to get weekly e-mails about the Perl programming language and related topics.
Want to see more? See the archives of all the issues.
Not yet subscribed to the newsletter? Join us free of charge!
(C) Copyright Gabor Szabo
The articles are copyright the respective authors.
Published on Monday 14 October 2024 01:19
The examples used here are from the weekly challenge problem statement and demonstrate the working solution.
You are given an array of integers, @ints. Write a script to find if there exist two indices $i and $j such that:
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!
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.
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.
$ perl perl/ch-1.pl 1 0 1
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.
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.
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.
MAIN:{
say luhn q/17893729974/;
say luhn q/4137 8947 1175 5904/;
say luhn q/4137 8974 1175 5904/;
}
◇
Fragment referenced in 7.
$ perl perl/ch-2.pl 1 1 0
Welcome to “What’s new on CPAN”, a curated look at last month’s new CPAN uploads for your reading and programming pleasure. Enjoy!
Welcome to “What’s new on CPAN”, a curated look at last month’s new CPAN uploads for your reading and programming pleasure. Enjoy!
cat
but prefixes each line with the filenamesprintf
with Term::ANSI::Sprintf (LNATION)Published by Unknown on Sunday 13 October 2024 13:06
Published by Aishik Nath on Saturday 12 October 2024 05:35
Yes, you read that right. Just install Straberry Perl and gcc will be properly installed in your Windows machine.
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:
Total: * 61:23 TOTAL (HH::MM)
Published by Stuart J Mackintosh on Tuesday 08 October 2024 11:00
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.
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 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 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.
Published by Unknown on Sunday 06 October 2024 18:55
Published by Unknown on Sunday 06 October 2024 18:53
This is the weekly favourites list of CPAN distributions. Votes count: 59
Week's winner (+3): Parallel::ForkManager
Build date: 2024/10/06 16:52:41 GMT
Clicked for first time:
Increasing its reputation:
Published on Saturday 05 October 2024 21:02
The examples used here are from the weekly challenge problem statement and demonstrate the working solution.
You are given an array of integers, @ints. Write a script to find the third distinct maximum in the given array. If a third maximum doesn’t exist then return the maximum number.
The majority of the work can be done in a couple of lines. We need only sort the distinct integers in the list and then return either the third largest number or, if none exists, the largest.
sub third_maximum{
my %h;
do{ $h{$_} = undef } for
@_;
my
@sorted = sort {$b <=> $a} keys %h;
return $sorted[2] if
@sorted >= 3;
return $sorted[0];
}
◇
Fragment referenced in 2.
The rest of the code just tests this function.
MAIN:{
say third_maximum 5, 6, 4, 1;
say third_maximum 4, 5;
say third_maximum 1, 2, 2, 3;
}
◇
Fragment referenced in 2.
$ perl perl/ch-1.pl 4 5 1
Your task is to write a program that takes English text as its input and outputs a jumbled version
The rules for jumbling are given as follows:
Looking closer at these rules the main thing we need to concern ourselves with is jumbling the letters with the exception of the first and last. The use of map will ensure the words are processed in order. To make sure the first/last letters are unchanged also depends on detecting punctuation.
Punctuation is determined by a regex. We’ll keep track of the locations so we can add them back later, after jumbling.
Now that we have the punctuation accounted for let’s do the jumble. We’ll do this by generating permutations and randomly select one.
my $p = Algorithm::Permute->new(
[
@{$stripped}[1 ..
@{$stripped} - 2]]
);
my
@p;
if(
@{$stripped} > 2){
my
@r = $p->next();
{
push
@p, [
@r];
@r = $p->next();
redo if
@r;
}
$stripped = [$stripped->[0] ,
@{$p[rand
@p]} ,
$stripped->[
@{$stripped} - 1]];
}
$stripped = join q//,
@{$stripped};
◇
Finally, add the punctuation back in.
The rest of the code drives some tests.
MAIN:{
say q/in the ASCII range match all non-controls./;
say jumble qw/in the ASCII range match all non-controls./;
say q//;
say q/This handy module makes performing permutation.../;
say jumble qw/This handy module makes performing permutation.../;
}
◇
Fragment referenced in 9.
$ perl perl/ch-2.pl in the ASCII range match all non-controls. in the AISCI range macth all non-rloncots. This handy module makes performing permutation... Tihs handy mloude mkaes prifnremog prtaoimetun...
Published by alh on Friday 04 October 2024 11:31
Paul writes:
With the 5.40 release well out of the way, and freed from my PSC commitments, I managed to find a bit more time this month to actually write some useful code.
Hours:
2 = Improvements to op_dump()
for custom operators
1 = Improvements to op_dump()
on existing UNOP_AUX operators
11 = Additions to meta
module: various "list"-type methods,
set_prototype + set_subname on metasubroutines, add_named_sub
helper method, is_class + is_method
Total: 14 hours
Published by Makoto Nozaki on Friday 04 October 2024 08:00
The Japan Perl Association made a generous donation to The Perl and Raku Foundation following their fundraising activity at YAPC::Hiroshima (article link). Here is a thank you message from Olaf Adler:
Japanese translation below:
日本語抄訳
こんにちは。Olaf Alderと申します。The Perl Foundationで後援者様向け広報の担当をしています。今日は日本のPerlコミュニティの皆様に感謝の意を表したく、ご連絡差し上げました。
Japan Perl AssociationとYAPC::Japanの皆様には、長年にわたるご支援を誠に「ありがとう」ございます。特に先日のYAPC::Hiroshimaの大盛況をお祝い申し上げます。写真で見た酒樽募金箱は印象的で、今後、私は日本酒を飲むたびにこのイベントを思い出すでしょう。
YAPCの継続的な成功は素晴らしいです。日本チームの秘訣を世界に伝えてほしいと願っています。私たちも多くを学びたいと思います。
Japan Perl AssociationはThe Perl Foundationの大切なパートナーです。今後とも協力し、Perlの発展に努めましょう。YAPC::Hakodateの盛会をお祈りしています。ありがとうございます!
Published by Mayur Koshti on Wednesday 02 October 2024 16:07
Published by TEJESWAR REDDY on Monday 30 September 2024 10:04