Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Meditations

( #480=superdoc: print w/replies, xml ) Need Help??

If you've discovered something amazing about Perl that you just need to share with everyone, this is the right place.

This section is also used for non-question discussions about Perl, and for any discussions that are not specifically programming related. For example, if you want to share or discuss opinions on hacker culture, the job market, or Perl 6 development, this is the place. (Note, however, that discussions about the PerlMonks web site belong in PerlMonks Discussion.)

Meditations is sometimes used as a sounding-board — a place to post initial drafts of perl tutorials, code modules, book reviews, articles, quizzes, etc. — so that the author can benefit from the collective insight of the monks before publishing the finished item to its proper place (be it Tutorials, Cool Uses for Perl, Reviews, or whatever). If you do this, it is generally considered appropriate to prefix your node title with "RFC:" (for "request for comments").

User Meditations
Beware of global! And bless the local!
3 direct replies — Read more / Contribute
by alexander_lunev
on Dec 12, 2019 at 03:40

    Hello monks.

    Today I found that a little negligence can cause a week-long debugging.

    I wrote a program that uses Crypt::OpenPGP module, and for a strange reason module works great when I simply initialize it with keyrings from file, but it crashes when i first read keyrings from files and combines them for my needs and then initialize module with constructed keyring objects. Terrible crashes of the Perl interpreter itself (sic!) was accompanied by cryptic messages like these:

    Win32::API::parse_prototype: WARNING unknown parameter type 'PVOID' at + C:/Strawberry32/perl/vendor/lib/Win32/API.pm line 568. Win32::API::parse_prototype: WARNING unknown parameter type 'ULONG' at + C:/Strawberry32/perl/vendor/lib/Win32/API.pm line 568. Win32::API::parse_prototype: WARNING unknown output parameter type 'IN +T' at C:/Strawberry32/perl/vendor/lib/Win32/API.pm line 600. Argument "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0..." + isn't numeric in subroutine entry at C:/Strawberry32/perl/vendor/lib +/Crypt/Random/Seed.pm line 247.

    I was wondering - what have i done to bring this punishment upon me? I compared objects that come out from keyring-file initialization and from keyring-objects initializations with Data::Dumper and couldn't find a difference. I even saved constructed keyring objects to files and initialize Crypt::OpenPGP with this newly created files - still all was crashing. The holy fear seized me and I decided to start my journey to the depth of module forest to find deliverance. I walk through Crypt::OpenPGP to Bytes::Random::Secure, to know that road leads - as it was told to me in the cryptic omen - to Crypt::Random::Seed, line 247, which was a Call to Win32::API function:

    my $rtlgenrand = Win32::API->new( 'advapi32', <<'_RTLGENRANDOM_PROTO_' +); INT SystemFunction036( PVOID RandomBuffer, ULONG RandomBufferLength ) _RTLGENRANDOM_PROTO_ return unless defined $rtlgenrand; return ('RtlGenRand', sub { my $nbytes = shift; my $buffer = chr(0) x $nbytes; my $result = $rtlgenrand->Call($buffer, $nbytes); # <= 247

    My journey comes to a dead end, for I didn't find deliverance there. And I started from the beginning of my code, turning lines of code off one by one. And I found it.

    This is the code that was a root of all misfortunes.

    open my $fh, "<", $file or die "can't open $file"; $/ = undef; my $key_string = <$fh>; close $fh;

    If you're enlightened enough, you will see my sin right away. I'm not enlightened enough to see it right away, but a doubt crawls into my mind - could it be the line $/ = undef;? I stared at this line for a minute and go search wisdom on the Internet. And then I found the Truth. And as always the Truth was under my nose all the time, but I couldn't see it. It should be local $/ = undef;!

    I don't know if it is clean and right way to read all file in a string, but even the great Gabor Szabo blesses slurp mode by setting $/ = undef;. But beware if you read his great article not thoroughly! The great misfortune awaits those who forget about local in a rush! Like me for example.

    You see? Setting $/ = undef; globally make things broken all the way up to the Perl interpreter itself, which was casting strange messages on his way to crash.

    But why would anyone write about it again, and again, and again? Because, as it said in every language:

    Repetitio mater studiorum est.

    Repetition is the mother of all learning.

    Wiederholen ist die Mutter des Studierens.

    La répétition est la mčre de la science.

    Повторение - мать учения.

    Let my mistake will be a lesson to others. Using global variables is always a risky and erroneous path, local variables is the only way to enlightenment. But this is the Truth that we were told from the beginning and we are still making this silly mistakes. And while we code simple programs, errors are simple and debuggable. But when we become more mature - so are the errors that we cause by violation of a simple rules that we doesn't learned well from the start. Beware of global! And bless the local! Amen.

RFC: "assignary" operator ?= :
7 direct replies — Read more / Contribute
by richard.sharpe
on Dec 07, 2019 at 11:01

    Hello guys,

    I would like having new type of assignment operator in perl, the combination of assignment and ternary operator (therefore calling it "assignary"):

    ?= :

    Not in context of regular expressions, not related with (?=) in any way, but in regular assignment. I haven't found something like that in perlop.

    Suggested meaning:

    $var ?= "something" : "something else";

    would be equivalent to:

    $var = $var ? "something" : "something else";

    Advantage of the first: more compact, as not writing $var two times.

    What do you think about possible existence of such hybrid of ternary and assignment operators?

Jumbo Signatures extensions discussion
2 direct replies — Read more / Contribute
by Corion
on Nov 29, 2019 at 02:14

    dave_the_m has posted a long and very comprehensive thread to perl5-porters in which he outlines his plans for subroutine signatures. The plan is to get a consensus on the syntax of the various features and then to implement them over the next year. The goal is to have subroutine signatures out of experimental status by Perl 5.36. Whatever breaking of backwards compatibility with the existing (experimental) subroutines is necessary should go into 5.32.

    I have mostly copied the Synopsis section of each mail here, and I really encourage you to look at the mails themselves which contain far more discussion of the proposed behaviours.

    The separate threads are:

    Jumbo Signatures extensions discussion - the top level thread

    Here is a contrived example of a signature which demonstrates many of the proposals. Some of it will make more sense after each proposal has been read.

    sub foo ( $self, # parameter declarations starting with '?' examine, # but don't consume any further arguments: ?*@args, # @args is set to the equivalent of @_ with one # arg shifted; i.e. like a slurpy but peeking ahead # and not actually consuming any args; the '*' means # that each @args element is aliased to a passed arg ?$peek_a, # $peek_a is bound to next arg but without consuming + it ??$has_a, # $has_a is set to true if there's an argument for $ +a $a, # normal scalar parameter ?{ print $a },# embedded code block - runs code; doesn't shift arg +s Dog $spot, # works the same as 'my Dog $spot' $b :shared, # you can use normal variable attributes $c :ro, # at compile time, $c in lvalue context croaks \@ary, # aliases @ary to a passed array reference \%hash, # aliases %hash to a passed hash reference *$scalar, # aliases $scalar to the next argument # Constraints and coercions: $d!, # croak if $d not defined $e isa Foo::Bar, # croak if $e isn't of that class $f is Int where $_ > 0, # croak if $f not a positive integer $x = 0, # a default value $y?, # short for $y = undef \@array?, # short for \@array = [] :$name1 = 0, :$name2 = 0, # consume name-value pairs (name1 => ..., name2 => . +...) @rest # slurp up any remaining arguments ) { .... }

    Parameter Attributes

    sub f ($x :foo, $y :bar(baz) bar2(baz2), ...) { ... }

    analogous to:

    my $x :foo; my $y :bar(baz) bar2(baz2);

    Perl should support parameter attributes.

    What exactly should the semantics be? Lets first review the current syntax as applied to 'my' declarations:

    my ($x, $y) :foo(foo_arg) :bar(bar_arg);

    is roughly equivalent to

    use attributes (); my ($x,$y); attributes->import(, __PACKAGE__, \$x, "foo(foo_arg)", "bar(bar_ar +g)"); attributes->import(, __PACKAGE__, \$y, "foo(foo_arg)", "bar(bar_ar +g)");

    Named Parameters

    sub foo ( $pos1, # positional parameter; consumes 1 arg $pos2, # positional parameter; consumes 1 arg :$name1, # named parameter, consumes ("name1", value) arg +pair :$name2, # named parameter, consumes ("name2", value) arg +pair @rest, # consumes all unrecognised name/value pairs ) { ... }

    This seems a popular feature request: give Perl 5 something similar to Perl 6's named parameters.

    Querying Parameters

    ?$x peek ahead to the next arg ??$x peek ahead and see if there is a next arg ?@a peek ahead and copy all remaining args ?%h peek ahead and copy all remaining key/val arg pairs ?{ code } execute some code without consuming any args

    Sometimes you want to find out some extra information about the arguments and the state of argument processing. With @_ available, this can be done, if messily; if @_ isn't populated (see the "@_ Suppression" thread), then it becomes harder/impossible, unless some other mechanisms are added.

    @_ suppression

    @_ will not be set, unset or localised on entry to or exit from a signatured sub; it will still be the @_ of the caller. But any use of @_ within the lexical scope of sub a sub will warn.

    Aliasing and Read-only variables

    sub foo { # the lexical vars $a, @b and %c are aliased to the things poi +nted # to by the reference values passed as the first three argumen +ts: \$a \@b, \%c, # $d is aliased to the fourth arg: *$d, # $e is aliased to the fifth arg, but at compile time, any us +e # of $e in lvalue context within this lexical scope is a compi +le # time error: *$e :ro, # the elements of @f are aliased to any remaining args, # i.e. a slurpy with aliasing ...: *@f # .. or a slurpy hash; every second remaining arg is aliased t +o # the hash's values: *%g ) { ... }

    Type and Value Constraints and Coercions

    sub f( $self isa Foo::Bar, # croak unless $self->isa('Foo +::Bar'); $foo isa Foo::Bar?, # croak unless undef or of tha +t class $a!, # croak unless $a is defined $b is Int, # croak if $b not int-like $c is Int?, # croak unless undefined or in +t-like $d is PositiveInt, # user-defined type $e is Int where $_ >= 1, # multiple constraints $f is \@, # croak unless array ref $aref as ref ? $_ : [ $_ ] # coercions: maybe modify the +param ) { ...};

    It seems that people express a desire to be able to write something like:

    sub f (Int $x) { ... }

    as a shorthand for for something like:

    sub f ($x) { croak unless defined $x && !ref($x) && $x =~ /\A-?[0-9]+\Z/; ....; }

    Similarly people want

    sub f (Some::Arbitrary::Class $x) { ... }

    as a shorthand for

    sub f ($x) { croak unless defined $x && ref($x) && $x->isa(Some::Arbitrary::Class); ...; }

    Furthermore, there are also Perl 6 generic constraints:

    sub f ($x where * < 10*$y) { ... }

    Scope and Ordering

    We need to determine and document how the various parts of a signature behave as regards to lexical scope, visibility, tainting and ordering of things like default expressions and constraints.

    dave_the_m proposes for lexical scoping that:

    sub f($a, $b, $c, ... ) { BODY; }

    Is logically equivalent to:

    sub f { my $a = ....; my $b = ....; my $c = ....; ....; BODY; }

    In particular, each parameter element is independent taint-wise, and each parameter variable has been fully introduced and is visible to default expressions and the like in further parameters to the right of it.

    Miscellaneous suggestions

    This last post contains are a few random suggestions that people have made at various times.

Custom date calculations using Date::Manip
No replies — Read more | Post response
by cavac
on Nov 27, 2019 at 12:57

    Some time ago, i uploaded Acme::September::Eternal to cpan. Then, on request by stevieb at Re^3: Help with my crap, i got a variant of that project.

    To quote: "I'm Canadian, so for us folk, it would be preferred if it was eternaldecemberize() where there's a single month of warm weather (August), and the rest December"

    I have uploaded Acme::December::Eternal to CPAN. But before that, i wrote a small test program to check out the math involved. The premise is that the year starts on 1st of August, and except of August everything else is the month of December. Let's take a look (you might need to click, i've put most of the article into a readmore tag)...

    Note: This is still technically incorrect, because there have been instances where countries skipped days on the calendar. For example, Samoa skipped the 30th of December 2011 so they could get to the other side of the dateline for some business reason. I'll have to fix my CPAN module to account for that kind of stuff.

    print $outstring, "\n";

    We output the calculated date string and we are done.

    Note 2: Calculating exact dates in the future is not possible, no matter how good your date library is. Not only for reasons like countries skipping (or adding) days, switching calendars, changing timezones on short notice or redefining daylight savings time (or banning/reintroducing it) willy-nilly after every change of government. No, even if you could fix all that (hint: go into politics), the nice folks at the International Earth Rotation and Reference System Service who keep our atomic clocks in sync with our solar system release a new Bulletin C twice a year to tell you if there is going to be a leap second at the end of the six month period. So, good luck estimating future timestamps ;-)

    perl -e 'use Crypt::Digest::SHA256 qw[sha256_hex]; print substr(sha256_hex("the Answer To Life, The Universe And Everything"), 6, 2), "\n";'
a lot of the CPAN big hitters have gone
3 direct replies — Read more / Contribute
by tobyink
on Nov 26, 2019 at 03:50

    I know I'm guilty of disappearing for extended periods myself. I understand that family, jobs, life can give people less time to contribute to open source projects. But it's somewhat concerning that a lot of major CPAN authors who have written some pretty useful modules seem to be disappearing lately. None of the following authors have made a release in the last 12 months:

    • ADAMK - Params::Util, DBD::SQLite
    • DOY - Eval::Closure
    • FLORA - Term::ReadLine
    • KENTNL - HTML::Tree
    • MSCHILLI - Log::Log4perl
    • MSCHWERN - Test::More, Method::Signatures
    • NUFFIN - KiokuDB, Try::Tiny
    • RCLAMP - File::Find::Rule, Pod::Coverage
    • RSRCHBOY - MooseX::AttributeShortcuts
    • STEVAN - Moose
    • TIMB - DBI, Devel::NYTProf
    • SIMONW - Module::Pluggable

    (Honorable mentions to INGY, DAGOLDEN, and RSAVAGE who have barely released anything in the last 12 months.)

    Many of their projects have gotten new maintainers, and there are always new CPAN authors coming up and releasing some great new things, but we do seem to be losing some key people who have made important contributions to the Perl ecosystem.

New berrybrew installer; Looking for testers
3 direct replies — Read more / Contribute
by stevieb
on Nov 22, 2019 at 13:45

    I recently had one of my clients ask me if I could automate installing berrybrew along with specific existing and new Perl instances.

    I've taken a couple of days to get things to the point where my release automation is doing the right thing. I've tested it on a half dozen Windows 10 VMs, and things appear to work correctly. That said, I probably have differing configurations on my Windows machines than others do, so I'm hoping I can get some volunteers to test it out and see if there are any oddities.

    The installer will install the 1.27 version, and is located right here.

    Defaults that should be visible throughout the process:

    • License should be displayed
    • Install directory should be "C:\Program Files (x86)\berrybrew"
    • "Install Perl 5.30.0_64" should be displayed as a component, and checked
    • You should see a couple of cmd windows open and close, then, if you've left the Perl install checkbox checked, a third cmd window will remain open displaying install progress. It should close upon completion

    After the install is complete:

    • echo %path% in a newly-opened cmd window should list "C:\Program Files (x86)\berrybrew\bin", and if you opted to install Perl 5.30.0 during install, you should see three paths all which should reflect "C:\berrybrew\5.30.0_64"
    • perl -V should be 5.30.0

    Uninstall: The uninstall program is inside of the install directory (by default, "C:\Program Files (x86)\berrybrew". After it's run, you should see (in yet another new cmd window:

    • Both the berrybrew path should be gone, as should all three of the Perl paths that were created
    • The "C:\Program Files (x86)\berrybrew" directory should remain, but be empty (I'm working on the removal of that dir)
    • The "C:\berrybrew" directory should still exist, and so should the 5.30.0_64 directory within it

    Re-installing after an uninstall will know if you've still got 5.30.0 installed and will bypass that part, but will "switch" to it before exiting.

    I'm also wondering if any UAC/security warnings or boxes pop-up during install.

    Thanks all!

    -stevieb

Perl Feels Good
4 direct replies — Read more / Contribute
by Anonymous Monk
on Nov 17, 2019 at 13:02
    I wrote another really cool Perl program today! It's 200 lines of pure awesomeness. 140 lines are code with 7 subroutines using a couple of spiffy core modules. It has 40 lines of embedded documentation and a 20 line __DATA__base! It was working so good when I imagined how to make it into a module and *presto* an hour later it was a 250 line module with those smooth method chains.

    I do this so often my ~/bin has over 1000 programs and modules. One of these days I would like to upload them somewhere if it's not too complicated. Until then I am a one man CPAN ;-)

    My projects include command line programs, web apps, search engines, linguistic analysis, os enhancement, graphics, data visualization, and making Perl easier to use by exposing its buried treasures.

    What are you doing with Perl?


    "I think that TPF (The Perl Foundation) would be wise to expand its scope to Perl software projects in a similar manner to ASF (Apache Software Foundation)."--PerlDean
    https://old.reddit.com/r/perl/comments/dq1lzy/the_perl_masterplan/f65h3t6/
Moo and command line scripts
1 direct reply — Read more / Contribute
by boftx
on Nov 08, 2019 at 20:02

    Hello fellow monks! It is good to once again tread these hallowed halls after all these moons of moons.

    I have been a fan of modulinos (thanks Brian D'Foy!) for a long time now because of the advantages for testability. I have also been a fan of Moo for several years. And of course, like many others, I have combined both techniques with Getopt::Long. I have also been using a standard set of command line options such as "--debug" and "--help", with "--debug" defaulting true so "--nodebug" is required to turn it off.

    In an effort to reduce boilerplate and a lot of copy-and-paste I wrote a simple Moo role to handle the basics for me. I have since refined it with a proper test suite and POD and it has now been released as MooX::Role::CliOptions. I would greatly appreciated any feedback from my brothers and sisters of the Monastery on any and all aspects.

    I am well aware that there are other ways of doing this, including a couple of other modules on CPAN. I hope that some will find this new Role to be easier to use in some respects, as well as being more "Moo-ish".

    You must always remember that the primary goal is to drain the swamp even when you are hip-deep in alligators.
Mozilla IoT platform Perl wrapper
4 direct replies — Read more / Contribute
by stevieb
on Oct 31, 2019 at 18:35

    As many of you know, I've spent the last four plus years working on software that allows us Perl hackers to muck with the Raspberry Pi.

    Although the uptake is relatively small, it has been a very enjoyable experience for me providing this for the community, especially given that I've received welcome and helpful feedback, along with bug fixes and wonderful criticism throughout it all.

    Now, Mozilla is opening up their IoT Platform with both REST and WebSocket APIs for the masses. I've been following it for a little while to see where it goes.

    I've already thrown out the question on my Perl blog, but it means more to me to ask here on Perlmonks; would it be worth my time to ensure Perl has an interface to it?

    -stevieb

equal treatment
1 direct reply — Read more / Contribute
by Anonymous Monk
on Oct 26, 2019 at 18:26

    I was writing a Perl version of a Python version of a Mac-centric Shell version of a BASIC program when there was a node about unequal treatment and I noticed that my finished perl and the original BASIC were both exactly 23 lines including the comment line added to each program and I could make an interesting node with a cute title that is a direct hyperlink to the source:

    Perl

    # https://www.perlmonks.org/index.pl?node=equal+treatment system 'clear'; print "Hello there. I'm a computer. What's your name? "; chomp($_ = <STDIN>); print "Hello ".$_.". You are welcome to computer land."; while () { print "What would you like to do today? 1) Say something random 2) Make a maze 3) Exit Enter your selection "; chomp($_ = <STDIN>); if (/1/) { system 'say', do { @_ = split /\n/, do{local(@ARGV,$/)="/usr/share/dict/words";<>}; $_[int rand@_] } } elsif (/2/) { print rand() < 0.5 ? '/' : '\\' for 1..3000 } elsif (/3/) { print "Bye"; exit } else { print "Try again." } }

    Python

    # https://news.ycombinator.com/item?id=20127987 import os import random import sys os.system("clear") print "Hello there. I'm a computer. What's your name?" G = raw_input() print "Hello " + G + ". You are welcome to computer land." while True: print "" print "What would you like to do today?" print "1) Say something random" print "2) Make a maze" print "3) Exit" print "Enter your selection" S = raw_input() if S == "1": F = open("/usr/share/dict/words").readlines() W = random.choice(F) os.system("say {}".format(W)) elif S == "2": for i in range(1, 3000): if random.random()>0.5: sys.stdout.write("/") else: sys.stdout.write("\\") elif S == "3": print "Bye." exit() else: print "Try again."

    Shell

    # https://news.ycombinator.com/item?id=20123365 clear echo "Hello there. I'm a computer. What's your name?" read G echo "Hello $G. You are welcome to computer land." while true do echo "" echo "What would you like to do today?" echo "1) Say something random" echo "2) Make a maze" echo "3) Exit" echo "Enter your selection" read S if [ "$S" = "1" ]; then echo $( head -n $((7*RANDOM)) /usr/share/dict/words | tail -n 1 ) elif [ "$S" = "2" ]; then for i in {1..3000}; do if (($RANDOM>16384)); then printf '/'; else printf '\'; fi done elif [ "$S" = "3" ]; then echo "Bye." exit else echo "Try again." fi done

    BASIC

    REM https://news.ycombinator.com/item?id=20118639 5 CLS 7 RANDOMIZE TIMER 10 PRINT "Hello there. I'm a computer. What is your name?" 20 INPUT G$ 30 PRINT "Hello "+G$+". You are welcome to computer land." 40 PRINT "What would you like to do today?" 50 PRINT "1) Make noises" 60 PRINT "2) Make a maze" 70 PRINT "3) Exit" 80 PRINT "Enter your selection:" 100 INPUT S$ 110 IF S$="1" GOTO 200 120 IF S$="2" GOTO 300 130 IF S$="3" GOTO 400 140 PRINT "Try again." 150 GOTO 40 200 SOUND 20+(RND*20000), RND*3 210 GOTO 200 300 SCREEN 1 310 IF RND>.5 THEN PRINT "/"; ELSE PRINT "\"; 320 GOTO 310 400 PRINT "Bye."
    Analysis of punctuation in each langage:
    cat hello.pl | perl -ne '$_=join"",<STDIN>;@_=$_=~/[^A-Za-z0-9\s]/g;print@_'; echo""
    
    '';".'.'?";($_=<>);"".$_."..";(){"?)))";($_=<>);(//){'',{@_=/\/,{(@,$/)="////";<>};$_[@_]}}(//){()<.?'/':'\\'..}(//){"";}{"."}}
    
    
    cat hello.py | perl -ne '$_=join"",<STDIN>;@_=$_=~/[^A-Za-z0-9\s]/g;print@_'; echo""
    
    .("")".'.'?"=_()""++"..":"""?"")"")"")"""=_()=="":=("////").()=.().("{}".())=="":(,):.()>.:..("/"):..("\\")=="":"."():"."
    
    cat hello.sh | perl -ne '$_=join"",<STDIN>;@_=$_=~/[^A-Za-z0-9\s]/g;print@_'; echo""
    
    ".'.'?""$..""""?"")"")"")"""["$"=""];$(-$((*))////|-)["$"=""];{..};(($>));'/';'\';["$"=""];".""."
    
    cat hello.bas | perl -ne '$_=join"",<STDIN>;@_=$_=~/[^A-Za-z0-9\s]/g;print@_'; echo""
    
    ".'.?"$""+$+"..""?"")"")"")"":"$$=""$=""$="""."+(*),*>."/";"\";"."
    
    
    Last but not least:
    use Inline Python => <<'END'; # paste the py code here and run under perl! =) END

    I guess replace "say" with "print" ("echo" for shell) if $^O ne 'darwin'

The missing link between "you may need to install the module" and "distribution installed" application is running!
4 direct replies — Read more / Contribute
by Anonymous Monk
on Oct 24, 2019 at 07:57
    You may try a perl app and see Can't locate Foo/Bar.pm in @INC (you may need to install the Foo::Bar module) (@INC contains: ...

    So you install the Foo::Bar module and try again and see Can't locate Bar/Baz.pm in @INC (you may need to install the Bar::Baz module) (@INC contains: ...

    So you install the Bar::Baz module and the application runs.

    Module::Load::Conditional (core) can reduce the pain to:

    Install required modules Foo::Bar Bar::Baz from CPAN? (y)/n y
    Use 1. cpan or 2. cpanm 1/(2) 2
    Successfully installed Foo::Bar
    Successfully installed Bar::Baz
    
    Or select 'n' for something more than @INC:
    Install required perl modules:
    cpan Foo::Bar Bar::Baz 
    cpanm -v Foo::Bar Bar::Baz 
    
    Can't locate Foo::Bar Bar::Baz in @INC (@INC contains: ...
    
    Should perl be doing something like this on the core level?

    Should monks adopt this mess or fold it into a module so it becomes a best practice?

    How could this idea be improved?

    Thank you!

    #!/usr/bin/perl use strict; use warnings; #use Foo::Bar; #use Bar::Baz; use Module::Load::Conditional 'can_load'; BEGIN { my $modules = [ map {$_} qw[ IPC::Cmd Foo::Bar Bar::Baz ]]; my @install = do { local @_; for my $m (@$modules) { push @_, $m unless can_load(modules => {$m,undef}, autoload => 1)} @_ }; @install and do { print 'Install required modules ', join(' ', @install), ' from CPAN? (y)/n '; my $in = <STDIN>; chomp $in; $in ||= 'y'; my $cpanm = IPC::Cmd::can_run('cpanm'); if (lc $in eq 'y') { if ($cpanm) { print 'Use 1. cpan or 2. cpanm 1/(2) '; my $cpan = do { local $_ = <STDIN>; chomp $_; $_ ||= 2; $_ = 2 unless /^1|2$/; $_ }; if ($cpan == 2) { unless (system $cpanm, '-v', @install) { system 'perl', $0, @ARGV; exit } } } unless (system 'cpan', @install) { system 'perl', $0, @ARGV; exit } } else{ die "Install required perl modules:\n". join ' ', 'cpan', @install, "\n". ($cpanm ? join(' ', 'cpanm', @install) : '')."\n\n". "Can't locate ".join(' ',@install).' in @INC '. '(@INC contains: '.join(' ', @INC).") \n" } }; Bar::Baz->import('Something')}
use all core modules, pragmas and extensions
1 direct reply — Read more / Contribute
by Anonymous Monk
on Oct 23, 2019 at 10:55
    I wondered what would happen if one were to use all core modules. Here's what happened:

    19 core libs can not be simply used, without being fatal, so they're commented out (ymmv on versions ne 5.26.2).

    The perl interpreter grows to about 150 megabytes.

    A series of warnings is printed which may or may not have any value. This is why I'm sharing it here. In case the warnings indicate real issues, or interesting things to investigate.

    This 1-liner generates the ~650 line script, redirects stdout to the file "useallcore" and runs "perl useallcore" which prints the errors, and lines from ps about the perl process.

    perl -MExtUtils::Installed -MModule::Metadata -e '$not=q/_charnames|au +touse|blib|charnames|Devel::Peek|encoding|encoding::warnings|feature| +File::Spec::VMS|filetest|GDBM_File|if|O|ok|open|Pod::Simple::Debug|so +rt|Thread|threads/;$not={map{$_=>1}split/\|/,$not};print"#!/usr/bin/p +erl\n# Load all core Perl modules, pragmas and extensions\n# Exceptio +ns, to prevent errors:\n".(join "\n", map {"#$_"} sort {lc$a cmp lc$b +} keys %$not).")\n\n";@_=grep/\.pm/,(ExtUtils::Installed->files("Perl +"));for(@_){$m=Module::Metadata->new_from_file($_)->{module} or next; +push@m,$m}for(sort{lc$a cmp lc$b}@m){print $not->{$_}?"#":"","use $_; +\n"}print"\nprint `ps -v | grep \"\$\$\"`;\n"' > useallcore; perl use +allcore
If Perl 5 were to become Perl 7, what (backward-compatible) features would you want to see?
11 direct replies — Read more / Contribute
by haukex
on Oct 14, 2019 at 10:06

    Disclaimer: This post is entirely hypothetical. No decisions regarding Perl 5 have been made, or to my knowledge even been seriously discussed. It's entirely possible that Perl 5 will stay Perl 5 forever, or that the "5" will simply be dropped from the numbering (which would mean the next release of Perl is Perl 32), or something else happens.

    Now that Perl 6 has been renamed to Raku, that theoretically leaves open the possibility of Perl 5 upgrading to Perl 7. I've thought about what features would warrant a major version number change, and that's what I'm writing about here. My list is probably not complete, and I might update it if I think of more.

    First off, in my opinion, Perl should continue its tradition of being mostly backwards-compatible from release to release. If you want radical changes to the language, see Raku (and define your own slang) ;-)

    • Subroutine signatures need to come out of experimental
    • Smart matching should either be revamped, or removed entirely (Update: and if the latter, keep given as a topicalizer whose block can return a value)
    • Various other experiments should come out of experimental - e.g. refaliasing and declared_refs are IMHO pretty useful.
    • I'm not sure how this would be best implemented, but a "batteries included" Perl release would be nice. For example, one that includes Moo and other extremely common modules such as DBI. We might look to Strawberry Perl for an initial list.
    • Update 2019-11-17: Implicit use utf8; and STDIN, STDOUT, etc. default to UTF-8 as well.

    I imagine that, similar to Perl 6, a Perl 7 binary might be called perl7, with files being called .p7 or .pl7, .pm7, etc. Using this interpreter or this file extension would be the same as a use v7; (and turn on the corresponding feature bundle, etc.).

    Again, these are just hypothetical and unfinished thoughts of mine :-)

    Update: I accidentally created this post too early, sorry for all the additional edits. I'm done for now and further significant edits will be marked as such.

Quote about thinking of those who come after you.
2 direct replies — Read more / Contribute
by sbutton
on Oct 09, 2019 at 06:34
    Hi, I half remember a quote from way back along the lines of "When coding think about those who come after you, in case they do". I think it was from Tom Christiansen. Whenever I use it most people just look at me blankly, but that's perhaps part of the charm. Occasionally someone gets it. But after much searching, I can't find the original quote. Anyone got a link to it?
"Nonliteral literal" is just an expression.
1 direct reply — Read more / Contribute
by rir
on Sep 24, 2019 at 00:40
    With AoAs something like:
    my $ar = [ [ 'HEAD_goes_here', 'BODY_here' ], [ 'FOOT', 'FOOT', 'FOOT', 'FOOT' ] ];
    written as a template with the literals as documentation. After the not-finding and the not-thinking, I wrote a sub to walk AoAs and extract the references to the scalar elements. Doing it by hand, one might write:
    my $scalars_flattened = [ \$ar->[0][0], \$ar->[0][1], \$ar->[1][0], \$ar->[1][1], \$ar->[1][2], \$ar->[1][3] ];
    Its gist:
    my @flat = @{$_[0]}; while ( List::Util::any { 'ARRAY' eq ref $_ } @flat ) { @flat = map { 'ARRAY' eq ref $_ ? \(@$_) : \$_ } @flat; @flat = map { 'REF' eq ref $_ ? $$_ : $_ } @flat; }
    Fortunately only in testing did I find the less helpfully shaped templates like:
    $ar = [ 'HEAD', 'BODY', [ 'FOOT', 'FOOT', 'FOOT', 'FOOT'], ];
    I would die if I had one like that.

    Be well,
    rir


Add your Meditation
Title:
Meditation:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":


  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.
  • Log In?
    Username:
    Password:

    What's my password?
    Create A New User
    Chatterbox?
    and the web crawler heard nothing...

    How do I use this? | Other CB clients
    Other Users?
    Others imbibing at the Monastery: (8)
    As of 2019-12-13 21:31 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?

      No recent polls found

      Notices?