Published by khwilliamson on Tuesday 22 October 2024 14:48
Cleanup pod for pv_uni_display Correct an incorrect statement and use an =item list to make the flag behaviors stand out
Published by khwilliamson on Tuesday 22 October 2024 14:48
pv_uni_display() Don't assume input is valid This function naively assumed that it could do UTF8_SKIP on its input unchallenged. But it's actually less work to get the actual value; just change the call of the function it uses to translate the input, so that it returns the length.
Published by khwilliamson on Tuesday 22 October 2024 14:48
pv_uni_display(): Fix indentation These lines were indented an extra space, not a multiple of 4, nor even 2.
Published by khwilliamson on Tuesday 22 October 2024 14:48
pv_uni_display(): Declare as U8 to eliminate casts Every use of these variables expects them to be pointers to U8.
Published by khwilliamson on Monday 21 October 2024 21:17
perl_langinfo.h: Fix to work on Android See GH #22627. Glibc has a few locale categories that aren't used elsewhere, AFAIK. Android has a crippled implementation of them, in that it has none of the items that comprise the categories. In a typical langinfo.h, these are enum fields, so their existence can't be checked with an #ifdef, but in Android, everything is a #define, so much be checked with #ifdef. To get around this without writing a Configure probe, this commit just creates #defines when they are missing the category (which catches the non-Androids) or when using Android.
Published by Aristotle on Monday 21 October 2024 17:21
Someone keeps registering and posting articles with links to the “skale.space” domain despite the fact that I keep deleting them, so I thought I should reward them for their effort.
They are some kind of blockchain shop (yeah, shady activities, how uncharacteristic, right?), so I don’t know that my usual note that you might want to know that if you do business with them is all that relevant, but, there you go.
Published by /u/learnwithscholar on Monday 21 October 2024 15:48
Hi, I am installing braker and it requires a set of Perl modules to be installed. I am having a hard time installing the YAML::XS module. I am using Perl v5.38.
The Perl module was installed using cpanm
command, and when I run perldoc -l YAML::XS
it shows There is No documentation.
The directory, where the libraries and executables exist, was added to the PATH and PERL5LIB environment variable, and still the XS.pm
is missing in the YAML
folder.
I tried to re-install the library in two different ways: cpanm --local-lib=~/perl5 --reinstall YAML::XS
and cpanm --force -v YAML::XS
still not resolved.
What is happening here, should I install a different version of Perl? Is it possible to manually install YAML/XS.pm
?
Published by U. Windl on Monday 21 October 2024 08:04
I wrote a Perl program (5.18.2 using NET::LDAP
(perl-ldap-0.44-10.3.1.x86_64), both from SLES12 SP5) in an UTF-8 environment (LC_CTYPE="en_US.UTF-8"
, Emacs displays "UUU") that reads an UTF-8 encoded file, inserts some attribute values read from an OpenLDAP server, and then writes the result into an UTF-8 encoded file.
It seems I had to use
use utf8;
use open IO => ':locale';
use open ':std' => ':locale';
use feature qw(unicode_strings);
in addition to binmode $fh, ":utf8";
before writing the output to $fh
.
With these additions the string lengths inside Perl seem correct, and the output file, too.
However as I found out lately, attribute values from LDAP (the result of some $ldap->search()
) that contain non-ASCII characters (like a German Umlaut) are not correct.
As they looked to me like "double-encoded", I added decoding them like this (to create a hash reference for the entry, keyed by DN):
$data{$entry->dn} = {map {
$_ => [map { decode_utf8($_) } $entry->get_value($_)]
} $entry->attributes(NLK_NO_OPTIONS => 1)};
While working, this looks strange, and I wonder whether there is a more elegant solution (after all I don't really understand what's going on internally).
For testing I had created a user like this:
dn: uid=testuser,ou=people,dc=company,dc=org
cn: User Test
gidNumber: 54321
givenName: User
homeDirectory: /tmp/testuser
loginShell: /bin/bash
sn: Test
uid: testuser
uidNumber: 54321
objectClass: top
objectClass: posixAccount
objectClass: inetOrgPerson
displayName:: QsO2c2VyIFVtbGF1dCBpbSBOYW1lbg==
Without the fix the displayName
would be displayed as "Böser Umlaut im Namen", and after the fix it's displayed as "Böser Umlaut im Namen".
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 /u/davorg on Sunday 20 October 2024 15:53
submitted by /u/davorg [link] [comments] |
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 /u/niceperl on Saturday 19 October 2024 18:37
Published by Unknown on Saturday 19 October 2024 20:36
Hi I am new to this stuff
i want to use scriptthis perl script to simulate the https requests performed by the deep testing app (for realme devices)
now i need to run this script on (strawberry perl)
but i have no pc to do this
so how can i run perl script on termux
everytime i do this on termux
i get this
Published by /u/briandfoy on Friday 18 October 2024 22:00
The URI module took a short holiday, but quickly returned. Just for giggles, I'd like to see everyone react (positivily) to u/oalders in the Github issue:
There are people who take care of things so most people never notice when something goes wrong, and from the time I reported this to resolution was three hours (although the issue was already known, I think). That's some pretty good support right there, and we should fête over that.
For what it's worth, GitHub pays attention to these things. When I filed an issue about getting them to think about putting Perl in their Advisory Database, the number of reactions that issue got made them think about it (right now it's a whole process with scheduling dev time, etc). One of the ways to show that Perl is alive is to react to Perl things (um, that deserve it, not bot spam!).
Published by flakes on Friday 18 October 2024 14:17
Say that I have the following simple module, which has a new
method and a say
method.
package foo;
use strict;
use warnings;
sub new {
my $class = shift;
my $self = {};
bless $self, $class;
return $self;
}
sub say {
my $self = shift;
print join( ", ", @_ ) . "\n";
}
If I want to call this method, I can do so like this:
my $foo = foo->new();
$foo->say("foo", "bar");
Is it possible to call this method without parens, like I can for standalone functions?
When I try to do so, I get this error:
my $foo = foo->new();
$foo->say "foo", "bar";
# String found where operator expected at HelloWorld.pl line 8, near "->say "foo""
# (Missing operator before "foo"?)
# syntax error at HelloWorld.pl line 8, near "->say "foo""
# BEGIN not safe after errors--compilation aborted at HelloWorld.pl line 14.
To my understanding so far, this has something to do with the Perl compiler being able to understand what symbols are top level functions ahead of time. When using the standalone function Perl has enough information to understand this is a function call, whereas for methods on the blessed hash, Perl can't figure it out, and opts to treat it as a scalar context.
Is there any way to make this behavior possible?
My main motivation for this is creating a wrapper like structure for doing metric timings. e.g.
my $result = $timer->run $metric_name, sub {
call_some_expensive_method($some_vars);
};
If I use parens, I start fighting with my perltidy settings and get results like the following, which I find far less readable.
my $result = $timer->run(
$metric_name,
sub {
call_some_expensive_method($some_vars);
});
Another option I've been playing with is making a top level function that wraps the behavior, allowing the Perl compiler to understand the context correctly.
sub timed {
return shift->run(@_);
}
...
my $result = timed $timer, $metric_name, sub {
call_some_expensive_method($some_vars);
};
Published by Brett Estrade on Friday 18 October 2024 04:32
After hundreds of hours of work and support from lots of people, the long promised Journal is here. That link will take you to some more information, on there a link to purchase is available. All proceeds go to supporting future Issues and events of the SPC and Perl Community Organization. At this time, an electronic version is not available due to end-of-year time constraints.
It may seem silly, but we spent extra time making sure the book spine looks good on a bookshelf and will look even better as the Issues accrue. Get it while it's hot. ISBN-13: 9798218984748, 152 pages.
Some of us are currently preparing for a block of Science Perl Talks at the London Perl & Raku Workshop 2024. We appreciate the organizers of this event for the opportunity.
More will be posted after the LPW, but the SPC is hosting the Perl Community Conference, Winter 2024 on December 18th (Perl's 37th birthday! :-)). If you are interested in getting published in the next Issue of the SPJ (Winter 2024), we are still accepting extended abstracts, which is up to 1 full page in the Journal and a 5 minute lightning talk slot at the Winter Conference.
Published by Perl Steering Council on Friday 18 October 2024 00:39
This week, we talked about some recent (and less recent) p5p threads:
Published by laurent_r on Thursday 17 October 2024 12:46
These are some answers to the Week 291, Task 2, of the Perl Weekly Challenge organized by Mohammad S. Anwar.
Spoiler Alert: This weekly challenge deadline is due in a few days from now (on October 20, 2024, at 23:59). This blog post provides some solutions to this challenge. Please don’t read on if you intend to complete the challenge on your own.
A draw poker hand consists of 5 cards, drawn from a pack of 52: no jokers, no wild cards. An ace can rank either high or low.
Write a script to determine the following three things:
1. How many different 5-card hands can be dealt?
2. How many different hands of each of the 10 ranks can be dealt? See here for descriptions of the 10 ranks of Poker hands: https://en.wikipedia.org/wiki/List_of_poker_hands#Hand-ranking_categories
3. Check then the numbers you get in step 2 by adding them together and showing that they're equal to the number you get in step 1.
We need a subroutine (com
) for computing the binomial coefficient formula for: n choose k. The simplest formula is: n! / k! (n - k)!
But this leads to compute very large numbers that we then divide by other very large numbers. For example, 52!
has 68 digits:
52! = 80658175170943878571660636856403766975289505440883277824000000000000. So I prefer to use a formula that considerably simplifies the fraction: n * (n - 1) * ... * (n - k + 1) / k!
.
This ought to be faster, but that's not the point, since it is quite fast anyway; the point is that we avoid the risk of integer overflow during intermediate computations. There is no such risk in Raku, and probably also not in Perl, but there are many languages or programming environments that can't handle integers with 68 digits.
See the previous section above for explanations on the com
auxiliary subroutine, which really does the bulk of the work.
The poker-hands
does only one thing: it populates a hash with the various hand types and their frequencies. This Wikipedia page provides a table with the mathematical expression of the absolute frequency of each hand type. The code did not really need a separate subroutine and could have been inserted in the main code, but I find it clearer this way, in a separate subroutine.
The rest of the program basically displays the hash in a form hopefully readable to the human eye.
sub com ($n, $k) {
# Binomial coefficient formula for: n choose k
my $nr_of_com = ([*] ($n - $k + 1)..$n)/([*] 1..$k);
return $nr_of_com;
}
sub poker-hands (){
my %hands =
"0. RF" => com(4, 1), # Royal flush
"1. SF" => com(10, 1) * com(4, 1) - com(4, 1),
# Straight flush
"2. FK" => com(13, 1) * com(12, 1) * com(4, 1),
# Four of a kind
"3. FH" => com(13, 1) * com(4, 3) * com(12, 1)
* com(4, 2), # Full house
"4. Fl" => com(13, 5) * com(4, 1) - com(10, 1)
* com(4, 1), # Flush (excl. RF and SF)
"5. St" => com(10, 1) * com(4, 1)**5 - com(10, 1)
* com(4, 1), # Straight (excl. RF and SF)
"6. TK" => com(13, 1) * com(4, 3) * com(12, 2)
* com(4, 1) ** 2, # Three of a kind
"7. TP" => com(13, 2) * com(4, 2)**2 *com(11, 1)
* com(4, 1), # Two pairs
"8. OP" => com(13, 1) * com(4, 2) * com(12, 3)
* com(4, 1)**3, # One pair
"9. NP" => (com(13, 5) - com(10,1)) * (com(4, 1)**5
- com(4, 1)), # No pair (or High card)
;
return %hands;
}
my %hand-count = poker-hands;
my $num-hands = com 52, 5;
say "Total number of hands (direct count) => $num-hands";
for %hand-count.keys.sort -> $key {
say " - $key => ", %hand-count{$key};
}
say "Sum of the hands by type => ", [+] %hand-count.values;
This program displays the following output:
$ raku ./poker-hands.raku
Total number of hands (direct count) => 2598960
- 0. RF => 4
- 1. SF => 36
- 2. FK => 624
- 3. FH => 3744
- 4. Fl => 5108
- 5. St => 10200
- 6. TK => 54912
- 7. TP => 123552
- 8. OP => 1098240
- 9. NP => 1302540
Sum of the hands by type => 2598960
This program is essentially a port to Perl of the above Raku program. Please refer to the previous sections if you need explanations.
There is one important change, though: rather than using hand abbreviations (RF, SF, FK, etc.) for the hash keys, it uses hand full name (Royal flush, Straight flush, Four of a kind, etc.), leading to more explicit output.
use strict;
use warnings;
use feature 'say';
sub com {
# Binomial coefficient formula for: n choose k
my ($n, $k) = @_;
my $fact_k = 1;
$fact_k *= $_ for 1..$k;
my $nr_of_com_numerator = 1;
$nr_of_com_numerator *= $_ for ($n -$k + 1)..$n;
return $nr_of_com_numerator/ $fact_k;
}
sub poker_hands {
my %hands =
("0. Royal flush" => com(4, 1),
"1. Straight flush" => com(10, 1) * com(4, 1)
- com(4, 1),
"2. Four of a kind" => com(13, 1) * com(12, 1)
* com(4, 1),
"3. Full house" => com(13, 1) * com(4, 3)
* com(12, 1) * com(4, 2),
"4. Flush" => com(13, 5) * com(4, 1) - com(10, 1)
* com(4, 1), # Flush (excl. RF and SF)
"5. Straight" => com(10, 1) * com(4, 1)**5 - com(10, 1)
* com(4, 1), # Straight (excl. RF and SF)
"6. Three of a kind" => com(13, 1) * com(4, 3)
* com(12, 2) * com(4, 1) ** 2,
"7. Two pairs" => com(13, 2) * com(4, 2)**2
* com(11, 1) * com(4, 1),
"8. One pair" => com(13, 1) * com(4, 2) * com(12, 3)
* com(4, 1)**3, #
"9. No pair" => (com(13, 5) - com(10,1))
* (com(4, 1)**5 - com(4, 1)),
# No pair or High card
);
return %hands;
}
my %hand_count = poker_hands;
my $num_hands = com 52, 5;
say "Total number of hands (direct count) => $num_hands";
for my $key (sort keys %hand_count) {
printf " - %-20s => %-10i \n", $key, $hand_count{$key};
}
my $sum = 0;
$sum += $_ for values %hand_count;
say "Sum of the hands by type => ", $sum
This program displays the following output:
$ perl ./poker-hands.pl
Total number of hands (direct count) => 2598960
- 0. Royal flush => 4
- 1. Straight flush => 36
- 2. Four of a kind => 624
- 3. Full house => 3744
- 4. Flush => 5108
- 5. Straight => 10200
- 6. Three of a kind => 54912
- 7. Two pairs => 123552
- 8. One pair => 1098240
- 9. No pair => 1302540
Sum of the hands by type => 2598960
The next week Perl Weekly Challenge will start soon. If you want to participate in this challenge, please check https://perlweeklychallenge.org/ and make sure you answer the challenge before 23:59 BST (British summer time) on October 27, 2024. And, please, also spread the word about the Perl Weekly Challenge if you can.
To the old Perl programmers out there looking for a new language to learn, I suggest giving Julia a serious look. I haven't had a language bring me this much joy since when I first discovered Perl a long time ago. If Perl is the grandpa, Julia is the granddaughter, and she's a really smart girl. She hangs out with scientists all day helping them make sense of their data, and she does it with a unique style.
To be continued...
(There's so much I want to say, but I don't want to commit the time to write it all down right now.)
Published by mmartiss on Thursday 17 October 2024 00:51
I am trying to run an apache web server, which would take my html form, process it, and would give some kind of answer. I had problems installing cgi, configuring it, but I managed to do it. Now I am getting an error "internal server error" when I am trying to check the perl script using curl. When I check the apache error logs, it says that it aborted because of the 3 line, which is: use CGI qw(:standard);
Here is my simple code:
#!/usr/bin/perl
use strict;
use warnings;
use CGI qw(:standard);
use CGI::Carp qw(fatalsToBrowser);
# Enable taint mode
use diagnostics;
print "Content-type: text/html\n\n";
# print header(-type => 'text/html', -charset => 'utf-8').
# start_html('Form Submission Results');
my $sequence = param('sequence');
my $alignment_type = param('alignment-type');
my $organism = param('organism');
my $sequence_length = param('sequence-length');
my $confidence_level = param('confidence-level');
# Check for missing data
if (!$sequence || !$alignment_type || !$organism || !$sequence_length || !$confidence_level) {
print h1("Error: Missing Data");
print p("Please fill all the fields.");
print end_html;
exit;
}
# Basic validation (simulating complex processing)
if ($sequence !~ /^[ACGT]+$/i) {
print h1("Error: Invalid Sequence");
print p("Sequence must contain only A, C, G, or T for DNA.");
print end_html;
exit;
}
# Simulate processing
print h1('Sequence Alignment Results');
print p("Alignment Type: $alignment_type");
print p("Organism: $organism");
print p("Sequence Length: $sequence_length");
print p("Confidence Level: $confidence_level");
print end_html;
I have tried removing cgi use lines, then I get no error, but then server doesn't return anything.
Published by Phil Goetz on Wednesday 16 October 2024 19:11
I'm suddenly unable to run any Perl scripts under Cygwin. Every script I try to run crashes like this:
phil@TAICHI /cygdrive/h/bakE/new/virChecked
$ findFiles -s . -t /cygdrive/D/data-comp/text -u /cygdrive/E/new/virChecked/text -d -a .3
Can't load '/home/phil/perl5/lib/perl5/x86_64-cygwin-threads-multi/auto/Win32/File/File.dll' for module Win32::File: No such file or directory at /usr/lib/perl5/5.36/x86_64-cygwin-threads/DynaLoader.pm line 206.
at /usr/local/bin/findFiles line 24.
Compilation failed in require at /usr/local/bin/findFiles line 24.
BEGIN failed--compilation aborted at /usr/local/bin/findFiles line 24.
phil@TAICHI /cygdrive/h/bakE/new/virChecked
$ pushd /home/phil/perl5/lib/perl5/x86_64-cygwin-threads-multi/auto/Win32/File/
~/perl5/lib/perl5/x86_64-cygwin-threads-multi/auto/Win32/File /cygdrive/h/bakE/new/virChecked
phil@TAICHI ~/perl5/lib/perl5/x86_64-cygwin-threads-multi/auto/Win32/File
$ ls -l File.dll
-r-xr-xr-x 1 phil None 178K Jul 14 2021 File.dll*
Sometimes perl won't open File.dll; sometimes it won't open IO.dll. In either case, the DLL is always exactly where Perl is looking for it, with world read privs; but Perl won't load it.
Line 206 of Dynaloader.pm is
my $libref = dl_load_file($file, $flags) or croak("Can't load '$file' for module $module: ".dl_error());
A comment near the start of Dynaloader says:
The load function that dl_load_file() calls may require an absolute pathname.
I can't find where dl_load_file() is defined. It isn't in Dynaloader.pm; and the only module Dynaloader includes is Config, which also doesn't have it, and includes no other files.
I suspect that some Perl module has changed, with the result that dl_load_file doesn't convert Cygwin absolute pathnames to Windows absolute pathnames. I tried reinstalling Perl 5.36.3-1, but it didn't help. I also made a new Cygwin installation and installed Perl 5.40, but it behaved the same way.
Questions:
POSTSCRIPT added October 13: I've gotten a lot of comments, but not one person has yet answered the simple question of whether THEY currently have a working version of Cygwin Perl. Please, someone, if you have a recent Cygwin Perl that still works, say so.
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 horshack on Wednesday 16 October 2024 08:22
Windows, Visual Studio Code. I have installed the extension: "Perl Navigator" and perl is installed in my computer system, perltidy is installed. The code in a file is like this:
#!/usr/bin/perl
use strict;
use warnings ;
use Params::Validate;
my $x =4;
my $y = "AB";
What can I do to reformat this code with perltidy with Visual Studio Code?
In vim I do this:
ESC :1,$!perltidy
I installed several extensions for Visual Studio Code but none of these tell me how to use them.
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
For several years now, development and support of wxPerl, the interface library between Perl and wxWidgets, has stalled. The latest release was based on Perl 5.16 and wxWidgets 2.9.
Meanwhile some active users have made attempts to port wxPerl to newer versions of Perl and wxWidgets, with varying results. Microsoft Windows and Apple macOS provide additional challenges.
I believe in user-friendly desktop based GUI applications written in Perl and wxPerl is an excellent tool to develop these applications that are deployable across different desktop platforms. I hate to see wxPerl rusting away in the archives.
If you are using wxPerl and want to keep using it with recent
versions of Perl and wxWidgets, please join the mailing list.
As a start, I've set up a new, independent repo for wxPerl on GitHub.
It currently has two branches: wx30 and master.
Branch wx30 contains an updated version of the last 'official' release 0.9932, fixed for modern Perl and wxWidgets 3.0. I have released it on GitHub as Wx-0.9933.
The master branch has been updated with all necessary changes for wxWidgets 3.2. Also some constants and methods have been added to deploy some 3.2 functionality. I have released it on GitHub as Wx-3.001. More will be added in the future but will require help from Perl/XS experts.
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.
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 if there exist two indices $i
and $j
such that:
This seems relatively straight forward, but there is a massive gotcha that hopefully other Team PWC members also noticed. For this task, I loop through the list and see if a value that is twice its value exist.
However, if the value is '0' (and thus 0 × 2 = 0), I need to check that there were at least two zeros in the list.
def double_exists(ints: list) -> bool:
for i in ints:
if i * 2 in ints:
if i != 0 or ints.count(0) > 1:
return True
return False
$ ./ch-1.py 6 2 3 3
true
$ ./ch-1.py 3 1 4 13
false
$ ./ch-1.py 2 1 4 2
true
$ ./ch-1.py 1 3 0
false
$ ./ch-1.py 1 0 3 0
true
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.
I start this task by removing non-digit characters from the string, and turn the reversed string into a list of integers.
I then use the supplied formula, alternating between adding the value to count
or multiplying it by two and removing 9. If the resulting count
is divisible by 10, I return True
, otherwise I return False
.
def luhn_algorithm(s: str) -> bool:
s = re.sub('[^0-9]', '', s)
ints = [int(n) for n in s[::-1]]
count = 0
for pos, i in enumerate(ints):
if pos % 2 == 1:
i *= 2
if i > 9:
i -= 9
count += i
return count % 10 == 0
$ ./ch-2.py 17893729974
true
$ ./ch-2.py "4137 8947 1175 5904"
true
$ ./ch-2.py "4137 8974 1175 5904"
false
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:
These are the five most rated questions at Stack Overflow last week.
Between brackets: [question score / answers count]
Build date: 2024-10-06 16:50:53 GMT
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
Published by perlancar on Friday 27 September 2024 04:29
dist | author | abstract | date |
---|---|---|---|
Acme-CPANModules-MultipleDispatch | PERLANCAR | List of modules to do smart matching | 2024-08-18T00:05:41 |
Acme-CPANModules-UnixCommandVariants | PERLANCAR | List of various CLIs that are some variants of traditional Unix commands | 2024-08-26T09:48:48 |
Acme-Free-API-ChuckNorris | OODLER | Perl API client for the Chuck Norris Quote API service, https://api.chucknorris.io. | 2024-08-29T18:39:41 |
Acme-Free-API-Stonks | OODLER | Perl API client for the, top 50 stocks discussed on le'Reddit subeddit – r/Wallstreetbets, https://tradestie.com/apps/reddit/api/. | 2024-08-30T16:21:46 |
Acme-Free-API-Ye | OODLER | Perl API client for the Kanye Rest Quote API service, https://kanye.rest/. | 2024-08-28T16:39:49 |
App-BookmarkFeed | SCHROEDER | Create a RSS feed from Markdown files | 2024-08-05T16:33:07 |
App-optex-mask | UTASHIRO | optex data masking module | 2024-08-16T10:14:16 |
App-prefixcat | PERLANCAR | Like Unix `cat` but by default prefix each line with filename | 2024-08-09T12:33:04 |
Ascii-Text | LNATION | module for generating ASCII text in various fonts and styles | 2024-08-29T10:49:18 |
Autoconf-Template | BIGFOOT | autoconfiscation help scripts | 2024-08-06T09:26:35 |
Bio-EnsEMBL | ABECKER | Bio::EnsEMBL – Ensembl Core API | 2024-08-29T16:32:54 |
Business-ID-VehiclePlate | PERLANCAR | Parse Indonesian vehicle plate number | 2024-08-07T00:05:46 |
Catalyst-Plugin-Profile-DBI-Log | BIGPRESH | Capture queries executed during a Catalyst route with DBI::Log | 2024-08-29T23:41:08 |
Circle-Block | CHENGYU | the block module for Circle::Chain SDK | 2024-08-29T06:33:17 |
Circle-Chain | CHENGYU | The great new Circle::Chain! | 2024-08-29T02:33:58 |
Circle-Common | CHENGYU | the common module for Circle::Chain SDK | 2024-08-29T06:31:49 |
Circle-User | CHENGYU | the user module for Circle::Chain SDK | 2024-08-29T06:36:47 |
Circle-Wallet | CHENGYU | the circle chain SDK in PERL | 2024-08-29T06:36:58 |
DBIx-Squirrel | CPANIC | A module for working with databases | 2024-08-08T20:01:38 |
Dancer2-Session-DBI | EPISODEIV | DBI based session engine for Dancer | 2024-08-29T13:55:42 |
DateTime-Locale-FromCLDR | JDEGUEST | DateTime Localised Data from Unicode CLDR | 2024-08-01T22:59:44 |
Dist-Build-XS-Alien | LEONT | Dist::Build extension to use Alien modules. | 2024-08-31T19:19:30 |
File-ShareDir-Tiny | LEONT | Locate per-dist and per-module shared files | 2024-08-25T13:07:29 |
Github-ReleaseFetcher | TEODESIAN | Fetch either the latest or a particular named version of a file in a release from github | 2024-08-13T22:09:19 |
IO-SocketAlarm | NERDVANA | Perform asynchronous actions when a socket changes status | 2024-08-27T06:08:13 |
IPC-MicroSocket | PEVANS | minimal request/response or pub/sub mechanism | 2024-08-05T13:49:53 |
JIRA-REST-Lite | SHINGO | Lightweight wrapper around Jira's REST API | 2024-08-16T01:20:46 |
Langertha | GETTY | The clan of fierce vikings with axe and shield to AId your rAId | 2024-08-03T20:56:05 |
Locale-Unicode-Data | JDEGUEST | Unicode CLDR SQL Data | 2024-08-01T22:43:58 |
Map-Tube-Rome | GDT | Interface to the Rome tube map | 2024-08-27T16:01:05 |
MetaCPAN-Pod-HTML | HAARG | Format Pod as HTML for MetaCPAN | 2024-08-26T14:55:52 |
MooseX-JSONSchema | GETTY | Adding JSON Schema capabilities to your Moose class | 2024-08-03T20:36:33 |
Net-OpenSSH-More | TEODESIAN | Net::OpenSSH submodule with many useful features | 2024-08-09T00:03:26 |
Object-Pad-Operator-Of | PEVANS | access fields of other instances | 2024-08-22T11:30:12 |
OpenFeature-SDK | CATOUC | OpenFeature SDK for Perl | 2024-08-17T19:40:04 |
Plack-App-Catmandu-OAI | NJFRANCK | drop in replacement for Dancer::Plugin::Catmandu::OAI | 2024-08-23T07:58:26 |
Protocol-Sys-Virt-Devel | EHUELS | Development helper for Protocol::Sys::Virt and its dependants | 2024-08-31T20:48:14 |
Protocol-Sys-Virt | EHUELS | Transport independent implementation of the remote LibVirt protocol | 2024-08-31T21:36:13 |
Regex-Common | ARFREITAS | Provide commonly requested regular expressions | 2024-08-12T22:48:17 |
Rope-Cmd | LNATION | Command Line Applications via Rope | 2024-08-30T20:00:03 |
RxPerl-Extras | KARJALA | extra operators for RxPerl | 2024-08-06T10:18:15 |
Sah-SchemaBundle-DNS | PERLANCAR | Schemas related to DNS | 2024-08-04T00:05:19 |
Sah-SchemaBundle-Data-Sah | PERLANCAR | Sah schemas related to Data::Sah | 2024-08-11T00:06:03 |
Sah-SchemaBundle-DataSizeSpeed | PERLANCAR | Sah schemas related to data sizes & speeds (filesize, transfer speed, etc) | 2024-08-02T21:50:19 |
SlapbirdAPM-Agent-Dancer2 | RAWLEYFOW | Agent software for the Perl application performance monitor, Slapbird. slapbirdapm.com | 2024-08-25T20:49:02 |
SlapbirdAPM-Agent-Mojo | RAWLEYFOW | Agent software for the Perl application performance monitor, Slapbird. slapbirdapm.com | 2024-08-09T21:00:04 |
SlapbirdAPM-Agent-Plack | RAWLEYFOW | A Plack agent software for the Perl application performance monitor, Slapbird. slapbirdapm.com | 2024-08-18T02:37:49 |
Syntax-Keyword-Assert | KFLY | assert keyword for Perl | 2024-08-14T13:53:23 |
Task-MemManager | CHRISARG | A memory allocator for low level code in Perl. | 2024-08-25T23:42:18 |
Term-ANSI-Sprintf | LNATION | sprintf with ANSI colors | 2024-08-25T09:46:37 |
Tk-PodViewer | HANJE | Simple ROText based pod viewer. | 2024-08-20T20:06:36 |
kura | KFLY | Store constraints for Data::Checks, Type::Tiny, Moose and more. | 2024-08-18T13:31:06 |
Number of new CPAN distributions this period: 52
Number of authors releasing new CPAN distributions this period: 29
Authors by number of new CPAN distributions this period:
No | Author | Distributions |
---|---|---|
1 | PERLANCAR | 7 |
2 | CHENGYU | 5 |
3 | RAWLEYFOW | 3 |
4 | LNATION | 3 |
5 | OODLER | 3 |
6 | LEONT | 2 |
7 | TEODESIAN | 2 |
8 | JDEGUEST | 2 |
9 | GETTY | 2 |
10 | KFLY | 2 |
11 | PEVANS | 2 |
12 | EHUELS | 2 |
13 | EPISODEIV | 1 |
14 | SCHROEDER | 1 |
15 | NERDVANA | 1 |
16 | BIGFOOT | 1 |
17 | CHRISARG | 1 |
18 | ABECKER | 1 |
19 | SHINGO | 1 |
20 | KARJALA | 1 |
21 | BIGPRESH | 1 |
22 | NJFRANCK | 1 |
23 | ARFREITAS | 1 |
24 | HAARG | 1 |
25 | HANJE | 1 |
26 | GDT | 1 |
27 | UTASHIRO | 1 |
28 | CPANIC | 1 |
29 | CATOUC | 1 |
Published by perlancar on Friday 27 September 2024 04:28
dist | author | abstract | date |
---|---|---|---|
Acme-CPANModules-ModifiedHashes | PERLANCAR | List of modules that provide hashes with modified behaviors | 2024-07-13T02:14:33 |
App-GeometryUtils | PERLANCAR | Utilities related to geometry | 2024-07-07T00:05:12 |
App-LastStats | DAVECROSS | A module to fetch and display Last.fm statistics | 2024-07-28T17:34:18 |
App-PerlGzipScript | SKAJI | Gzip perl scripts to reduce their file size | 2024-07-20T12:49:29 |
App-YtDlpUtils | PERLANCAR | Utilities (mostly wrappers) related to yt-dlp | 2024-07-10T02:59:34 |
Astro-MoonPhase-Simple | BLIAKO | Calculate the phase of the Moon on a given time without too much blah blah | 2024-07-14T14:14:36 |
Audio-Cuefile-Libcue | GREGK | Perl interface to the libcue cuesheet reading library | 2024-07-19T19:43:23 |
Bencher-ScenarioBundle-SmartMatch | PERLANCAR | Scenarios to benchmark switch & smartmatch in Perl | 2024-07-03T09:45:27 |
CVSS | GDT | CVSS (Common Vulnerability Scoring System) command line interface | 2024-07-30T22:11:37 |
Catmandu-Store-OpenSearch | NJFRANCK | A searchable store backed by Opensearch | 2024-07-03T07:23:38 |
Consumer-NonBlock | EXODIST | Send data between processes without blocking. | 2024-07-02T19:53:48 |
Dancer2-Plugin-NYTProf | GEEKRUTH | NYTProf, in your Dancer2 application! | 2024-07-02T13:03:01 |
Data-LnArray-XS | LNATION | Arrays | 2024-07-12T09:58:12 |
Data-Random-Person | SKIM | Generate random person. | 2024-07-05T00:10:57 |
Exercises-API | NOBUNAGA | API Ninja's Exercises API | 2024-07-02T19:49:44 |
Extender | DOMERO | Dynamically enhance Perl objects with additional methods from other modules or custom subroutines | 2024-07-17T10:06:50 |
Kanboard-API | BARBARITO | A Perl interface to the Kanboard API | 2024-07-28T23:46:12 |
KelpX-Controller | BRTASTIC | Base custom controller for Kelp | 2024-07-08T14:43:24 |
MIDI-RtMidi-ScorePlayer | GENE | Play a MIDI score in real-time | 2024-07-10T23:51:51 |
Math-GSL-Alien | HAKONH | Easy installation of the GSL shared library | 2024-07-17T09:42:10 |
Number-Iterator-XS | LNATION | iterate numbers faster | 2024-07-26T03:56:33 |
OpenMP | OODLER | Metapackage for using OpenMP in Perl | 2024-07-19T21:12:29 |
Perl-PrereqScanner-Scanner-DistBuild | LEONT | scan for Dist::Build dependencies | 2024-07-12T12:03:35 |
Plack-App-Catmandu-SRU | NJFRANCK | drop in replacement for Dancer::Plugin::Catmandu::SRU | 2024-07-30T09:27:07 |
SPVM-Resource-Eigen | KIMOTO | Resource for C++ Eigen library | 2024-07-16T23:56:40 |
Sah-SchemaBundle-Country | PERLANCAR | Various Sah schemas related to country codes/names | 2024-07-14T00:05:31 |
Sah-SchemaBundle-Currency | PERLANCAR | Various Sah currency schemas | 2024-07-21T00:06:11 |
Sah-SchemaBundle-DBI | PERLANCAR | Schemas related to DBI | 2024-07-28T00:06:12 |
Shannon-Entropy-XS | LNATION | Calculate the Shannon entropy H of a given input string faster. | 2024-07-18T19:43:55 |
Slack-BlockKit | RJBS | a toolkit for building BlockKit blocks for Slack | 2024-07-04T01:51:26 |
String-Mask-XS | LNATION | mask sensitive data faster | 2024-07-03T21:44:29 |
Syntax-Operator-Is | PEVANS | match operator using Data::Checks constraints | 2024-07-08T14:59:03 |
TableData-Business-ID-Kemenkes-RDA | PERLANCAR | Indonesian RDA (AKG, Angka Kecukupan Gizi) | 2024-07-02T03:05:09 |
Text-Schmutz | RRWO | You̇r screen is quiṭe dirty, please cleȧn it. | 2024-07-11T22:41:24 |
Text-Template-Tiny | JV | Variable substituting template processor | 2024-07-05T11:10:37 |
Tk-Terminal | HANJE | Running system commands in a Tk::Text widget. | 2024-07-03T09:24:21 |
Tradestie-WSBetsAPI | NOBUNAGA | Tradestie's Wallstreet Bets API | 2024-07-01T19:57:16 |
WebService-GrowthBook | DERIV | … | 2024-07-02T11:17:20 |
Whelk | BRTASTIC | A friendly API framework based on Kelp | 2024-07-03T13:59:32 |
Win32-Console-DotNet | BRICKPOOL | Win32 Console .NET interface | 2024-07-29T07:05:25 |
Win32API-RecentFiles | CORION | recently accessed file API functions on Windows | 2024-07-29T18:16:24 |
Number of new CPAN distributions this period: 41
Number of authors releasing new CPAN distributions this period: 28
Authors by number of new CPAN distributions this period:
No | Author | Distributions |
---|---|---|
1 | PERLANCAR | 8 |
2 | LNATION | 4 |
3 | NJFRANCK | 2 |
4 | BRTASTIC | 2 |
5 | NOBUNAGA | 2 |
6 | OODLER | 1 |
7 | GENE | 1 |
8 | RJBS | 1 |
9 | SKAJI | 1 |
10 | DAVECROSS | 1 |
11 | GREGK | 1 |
12 | LEONT | 1 |
13 | GEEKRUTH | 1 |
14 | BARBARITO | 1 |
15 | EXODIST | 1 |
16 | HAKONH | 1 |
17 | GDT | 1 |
18 | DOMERO | 1 |
19 | BRICKPOOL | 1 |
20 | HANJE | 1 |
21 | SKIM | 1 |
22 | RRWO | 1 |
23 | JV | 1 |
24 | CORION | 1 |
25 | DERIV | 1 |
26 | BLIAKO | 1 |
27 | PEVANS | 1 |
28 | KIMOTO | 1 |