Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer


( #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
[RFC] File::Replace
2 direct replies — Read more / Contribute
by haukex
on Sep 20, 2017 at 05:50

    Many of you are probably aware of the pattern of opening a temporary file, reading from the original file and writing the modified contents to the temporary file, and then renameing the temporary file over the original file, which is often an atomic operation (depending on OS & FS). I recently wrote a module to encapsulate this behavior, and here is one of three interfaces that are available in File::Replace. There are several options to configure the behavior, including the ability to specify PerlIO layers, what happens if the file doesn't exist yet, etc.

    use File::Replace 'replace2'; my ($infh,$outfh) = replace2($filename); while (<$infh>) { # write whatever you like to $outfh here print $outfh "X: $_"; } close $infh; # closing both handles will close $outfh; # trigger the replace

    Since I hope this is something that you might find useful, I would be happy about any feedback you might have!

    To give a practical example, here is an update of my code from this node. As you can see I was able to get rid of eight lines of fairly complicated code, while keeping the main loop entirely unchanged. The module also adds some more robustness, as it incorporates a few more checks on whether operations were successful or not.

Encoding Decoding on multiple formats RFC
2 direct replies — Read more / Contribute
by thanos1983
on Sep 19, 2017 at 06:44

    Hello fellow Monks,

    I am looking for your advice on updating and my implemented module for encoding and decoding multiple formats. I wrote the module and tried to include as many formats I could. I know that there other formats that I have not added but in my case during the encoding decoding process has to be also converted to hex and vise versa, where I found problems with more formats that I have not included on my sample of code.

    The whole idea behind the module, I am working for a telecommunication company and part of my daily job is to correct problems. The languages can vary globally since it is a live network with live customers and the format is in hex on a variety of encoding patterns. I had some cases that I had to create small scripts to process the packages before and after the nodes so I can observe encoding corruptions or not. Sample of previous questions that I was working that are similar with the module (Chinese to Hex and Hex to Chinese, Arabic to Hex and Hex to Arabic). After seeing my self that I need more and more encodings for more and more languages I end up saying that I need to write a simple module to do that for me instead of creating more or less the same code again and again.

    So having said that, sample of code as the user would use the module based on the encodings that can be handled:

    The actual module, that I still have not found a good name to apply. Any ideas for naming please feel free to propose.

    The module by it self is extremely simple, but at the same time on my position and for my colleagues is extremely useful. Any suggestions on code or any other improvement please feel free to suggest.

    Hope this tiny module will help others also.

    BR, Thanos

    Seeking for Perl wisdom...on the process of learning...not there...yet!
Kindness and support for Meredith
No replies — Read more | Post response
by stevieb
on Sep 18, 2017 at 11:47

    This isn't about Perl; it's about the community.

    Early last week, I wrote in CB about a tremendously disturbing event that took place with my family.

    In response, several Monks reached out to offer condolences and offers of help.

    In my near absence from here since then, a bunch of Monks got together, and 1nickt reached out a few times to say that a group of Monks wanted to do something. Initially, I was advised that the offer could be in the form of finance for travel etc. After I carefully deliberated this kind gesture and discussed with my wife, I decided that I wouldn't feel comfortable taking any funds directly, so I let Nick know that it would be preferred to send flowers or donate to a charity instead.

    I was advised by Nick that a beautiful arrangement had been sent on behalf of the Monks, and any left over funds plus any more funds that may trickle in would be donated to some form of preventing violence charity. I advised Nick that I was too busy to deal with it, so I asked if he'd spearhead the decision of which one.

    I want to express my (and my wife's) deepest gratitude for such an overwhelmingly kind gesture by everyone involved; those who provided funding, as well as those who reached out to offer emotional support. I'd like to thank Nick directly as well for taking the time to organize everything he did.

    This goes to show that this is a great place of caring, not just another forum to get help with questions.

    Perlmonks is the only group I let in on what had happened, as it's the only online forum where I feel so comfortable, and people here came through with flying colours... the manner was absolutely unexpected; stunning actually.

    Thank you very much everyone, it's kind of hard to put into words, so instead, I'll just try to get back into the groove and give back the best way I can; by continuing to help those who need it here.



More Betterer Game of Life
2 direct replies — Read more / Contribute
by eyepopslikeamosquito
on Sep 18, 2017 at 03:11

    Without good design, good algorithms, and complete understanding of the program's operation, your carefully optimized code will amount to one of mankind's least fruitful creations - a fast slow program.

    -- Michael Abrash

    In High Performance Game of Life, I chose a very simple design, storing all live cells in a single set. Though pleasing for its simplicity and unboundedness, its drawback is that counting live neighbours becomes a hash lookup, a chronic performance bottleneck. What to do?

    Rather than spending more time optimizing my original design -- thus creating a "fast slow program" -- I researched the domain, learning of many different ways to do it. From the many possible approaches, I chose the simplest one I could find that looked interesting and enjoyable, and implemented it in pure Perl.

    To try to keep my initial attempt short and understandable, I started with a simplified version based on the the brilliant works of Adam P. Goucher (apg), tiling the universe with 64 x 64 tiles in a conventional way, each tile having eight neighbours. Note that this was chosen for simplicity; more efficient schemes are available, such as the "brick wall" tiling used by Goucher in later versions. For background on the concept of breaking the game of life universe into overlapping tiles, see this description of Life128 and vlife.

    My code is loosely based on apgnano (version 2) but advances one tick at a time (rather than two at a time, as apg did) and does not attempt to use universe history. Fair warning though. Despite striving to keep the code simple and short, it's way more complex than my original, swelling from 66 lines of code to 414.

    Benchmark Results

    I've updated the benchmark results given in my original node. As you can see, even this simplified version, with no attempts made at code optimization, is already an order of magnitude faster than the optimized version of the original.

    Version375K cells750K cells1.5 million cells3 million cells
    new (see below)1 secs1 secs3 secs6 secs (Mario improvements)13 secs26 secs52 secs108 secs (Original)35 secs70 secs141 secs284 secs
    Game::Life::Infinite:Board37 secs96 secs273 secs905 secs

    As for memory use, the maximum Windows Private Bytes used for the three million cell case by each process was:

    • New (see below): 700,000K
    • (Original): 1,455,004K
    • (Mario improvements): 1,596,368K
    • Game::Life::Infinite:Board: 18,138,504K

    Benchmark timings running AppleFritter's Lidka test for 30,000 ticks were:
    VersionLidka 30,000 ticks
    new (see below)58 secs (Mario improvements)450 secs (Original)1635 secs
    Game::Life::Infinite:Board640 secs

    Improving My Initial Attempt

    There is certainly plenty of scope for improving my initial attempt. After all, I have not attempted any optimizations at all, just tried to implement ideas from apg's C++/assembler programs in a pure Perl form in a simple and clear way. While all feedback is welcome, I'm especially eager to see:

    • Refactorings that make the Perl code shorter, clearer, more idiomatic.
    • Performance optimizations.
    • Explanations of (and alternatives to) the bit-twiddling code below, specifically the bit operations in st64_tiletick() below I find especially hard to follow.
    • Bug fixes. I was shocked when my code worked the second time I ran it - just one coding blunder was corrected before my new passed tgol.t, tgol2.t, tgol3.t and the 30,000 lidka test! So I suspect there may be more bugs lurking in this brand new implementation.
    As a minimum, any code refactorings should be tested by running tgol.t and tgol3.t from my original node. Note that this new version of is (or should be) 100% interface compatible with my original.

PBP in German out of print - solutions?
5 direct replies — Read more / Contribute
by LanX
on Sep 11, 2017 at 08:57

    I'm in the perverted situation that I want to equip my team with prints of Perl Best Practices and the German version is not only out of print, but O'Reilly is even not providing an eBook Version.

    In Germany it's legal to photocopy books which got out of print after two years.

    My best idea at the moment is to resort to copying relevant chapters of the German version and buying same amount of English version as compensation for bad conscience.

    What you think?

    PS: My colleagues do speak some kind of English but I don't want to accept the loss of productivity here.

    Cheers Rolf
    (addicted to the Perl Programming Language and ☆☆☆☆ :)
    Je suis Charlie!

Anniversary: five years a monk
No replies — Read more | Post response
by Laurent_R
on Sep 09, 2017 at 11:06
    Dear fellow brethren,

    I made profession and registered to this monastery just five years ago today. And since then, I connected to this forum almost every single day. And it has been a pleasure every time.

    Even though I asked only a few questions over these five years, but struggled much more to try to answer others' questions, I learned really a lot from reading posts from many fellow monks in this community. Over this five-year period, this site has made me knowledgeable about my favorite programming language more than anything else I have done in the meantime.

    Many thanks to you all, dear sisters and brothers. And long live Perl.


RFC: LSP for Perl
1 direct reply — Read more / Contribute
by RonW
on Sep 06, 2017 at 20:30

    When I went to to see if the latest major release was ready (it is, I'm late, as usual), I discovered something called "Language Server Protocol". Eclipse Oxygen supports it. Several other editiors/IDEs supposedly already support it.

    The idea is that instead of each editor/IDE needing a plug-in for each additional language some one wants to support, each editor/IDE gets a LSP client plug-in and each language gets a LSP server.

    I did some searching, but didn't find project creating a LSP server for Perl. Still, I think it would be a way to help get better support for Perl into the editors and IDEs that people want to use.

    So, sisters and brothers, what do you think? would you be willing to contribute (and how)?

    Thank you for your thoughts.

Chinese to Hex and Hex to Chinese
1 direct reply — Read more / Contribute
by thanos1983
on Sep 05, 2017 at 04:47

    Hello fellow Monks,

    I am trying to convert an Chinese string to hexadecimal (final form) and vise versa, but I wanted also to see the in between steps.

    I tried successfully to convert the string to utf-8 and then I was thinking of converting it into ascii characters and then to hex with the help of String::HexConvert. If that would work I would revert the process to the original form.

    I manage to accomplish my task for utf-8 and UCS-2 encoding. I though of sharing the script, since I was not able to find further information online.

    Similar question (How do I convert a sequence of hexes (D0 D6) to Chinese characters (中)?). I used the following modules (Text::Unidecode) and also (String::HexConvert).

    Sample of code:

    use utf8;
    use strict;
    use warnings;
    use feature 'say';
    use Text::Unidecode;
    use Encode qw(decode encode);
    use String::HexConvert ':all';
    binmode( STDOUT, ':utf8' );
    my $Chinese = '北亰'; # Chinese characters for Bei Jing (U+5317 U+4EB0)
    say 'UTF-8';
    my $utf8 = encode( 'UTF-8', $Chinese );
    my $ascii2hexUTF8 = ascii_to_hex($utf8);
    say join(' ', split(/(..)/, $ascii2hexUTF8));
    my $hex2ascciiUTF8 = hex_to_ascii($ascii2hexUTF8);
    my $strUTF8 = decode( 'UTF-8', $hex2ascciiUTF8);
    say $strUTF8;
    say unidecode( $strUTF8 );
    say '';
    say 'UCS-2';
    my $ucs2 = encode("UCS-2BE", $Chinese);
    my $ascii2hexUCS2 = ascii_to_hex($ucs2);
    say join(' ', split(/(..)/, $ascii2hexUCS2));
    my $hex2ascciiUCS2 = hex_to_ascii($ascii2hexUCS2);
    my $strUCS2 = decode("UCS-2BE", $hex2ascciiUCS2);
    say $strUCS2;
    say unidecode( $strUCS2 );
    $ perl
     e5  8c  97  e4  ba  b0
    Bei Jing
     53  17  4e  b0
    Bei Jing

    Hope this helps someone else as it did to me, BR.

    Seeking for Perl wisdom...on the process of learning...not there...yet!
Scope in use
5 direct replies — Read more / Contribute
by choroba
on Sep 04, 2017 at 04:35
    A colleague has asked me recently why the following ends in Global symbol "$lib" requires explicit package name:
    #! /usr/bin/perl use warnings; use strict; use lib my $lib = '.'; print $lib;

    My answer was that the code is equivalent to

    BEGIN { require lib; 'lib'->import(my $lib = '.'); }

    But I was kind of unhappy about it. Is it a feature that use creates a scope around its parameters, or was it just easier to implement it like that? Have you noticed the behaviour and what do you think about it?

    ($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,
A Few Impressions from Amsterdam
4 direct replies — Read more / Contribute
by haukex
on Aug 13, 2017 at 11:03

    I was originally going to post something else for my 1000th node, but I'll save that for later, since I think this is fitting: As many of you probably know, The Perl Conference in Amsterdam ended on Friday. It was my first Perl event, and a great experience! I was very happy to finally meet some of you in person, choroba, LanX, Corion, Tux, Laurent_R, and rurban, and I'm really sorry I didn't get to say bye properly since I had to leave a bit early. If I met some of you but haven't yet matched you to a username, I apologize and drop me a /msg.

    I enjoyed the talks by some of the greats like TimToady, TheDamian, Ovid, and brian_d_foy, some of which are already available as videos on Facebook (Update: and YouTube, thanks Corion), and I hear the full videos should be online within a month or so. For my favorite funny moment of the conference: First, watch Damian Conway's talk "Three Little Words", definitely worth it on its own (as is checking out the impressive PPR), and then go to the Lighting Talks from Aug 10th and skip ahead to around 1h39m15s in the video... :-)

    Update: Added direct links to the YouTube videos.

    Update 2: Some pictures can be found at Also updated links to YouTube.

How has Perl affected you?
8 direct replies — Read more / Contribute
by stevieb
on Aug 12, 2017 at 16:58

    Slow weekend afternoon, taking a break from packing up my life and doing a huge shift towards an entirely new adventure.

    I ran into Perl through my first non-contract job. I picked up an ISP that was barely more than a start-up, and with a book off of a shelf, I fell in love (Perl 4/early 5 days).

    Over the years, (but with 20/20 hindsight it started not long after I had to pick up Perl) I have come to appreciate the Perl community as a group who are loyal, dedicated and serious, all the while being able to take criticism quite well.

    I savored the day I became a Friar; it allowed me to take part in some decision making on this site, which imho is the de-facto place to find Perl experts.

    Since the first day I picked up that "Learn Perl in 21 Days" book, I've gone on to do a lot of interesting things, meet a lot of interesting people, learned more than what I've been able to share, and help a lot of people in this language (and thanks to it, other ones as well).

    I'm coming up on my 8th birthday here, so while taking a breather from the physical duties of life, thought I'd once again share my appreciation for Perlmonks, and ask you, newbie or not, why you are invested in Perl, what it has done for you, and whether it has changed anything regarding how you approach other tasks/problems in your day-to-day.


High Performance Game of Life
5 direct replies — Read more / Contribute
by eyepopslikeamosquito
on Aug 11, 2017 at 08:49

    The universe of Conway's Game of Life is an infinite two-dimensional orthogonal grid of square cells, each of which is in one of two possible states, alive or dead. Every cell interacts with its eight neighbours, which are the cells that are horizontally, vertically, or diagonally adjacent. At each step in time, the following transitions occur:

    1. Any live cell with fewer than two live neighbours dies, as if caused by under-population.
    2. Any live cell with two or three live neighbour lives on to the next generation.
    3. Any live cell with more than three live neighbours dies, as if by overcrowding.
    4. Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.
    The initial pattern constitutes the seed of the system. The first generation is created by applying the above rules simultaneously to every cell in the seed - births and deaths occur simultaneously, and the discrete moment at which this happens is sometimes called a tick (in other words, each generation is a pure function of the preceding one). The rules continue to be applied repeatedly to create further generations.

    -- Conway's Game of Life (wikipedia)

    I've recently been forced to become acquainted with Conway's Game of Life after being asked to assess various implementations of it submitted by job applicants. Rather than a chore, I actually found it very interesting. Not the GUI stuff, just the guts of the code. How to implement it cleanly, concisely, efficiently.

    I wrote a couple of solutions myself, in both Perl and C++11, which I present below. Though still a game of life novice, I've spent quite a bit of time on these solutions already - including some profiling and performance optimization of my C++ solution. My Perl solution is essentially a translation of the one I wrote first in C++.

    Having spent time analysing this problem, I'm interested to see how others go about it.

    The Challenge

    If you want to test yourself, and have a few hours to spare, you might like to have a go (without reading my solutions below) at implementing the above algorithm as a simple Organism class with methods:

    • insert_cells() - insert a list of live cells (x and y coordinates) into the Organism. This is used to set the starting state of the Organism.
    • count() - return the number of live cells in the Organism. This is used for verification by unit tests.
    • get_live_cells() - return the list of all cells currently alive in the Organism. This is also used for verification.
    • tick() - create the next generation of the Organism by applying the four rules above. This is where most of the hard work and performance challenges are.
    For this challenge, you don't need to be truly infinite, but you must handle cells with x and y co-ordinates in the -2 GB to 2 GB range (i.e. 32-bit signed integer x and y co-ordinates). In the interests of keeping the challenge smallish, you don't need to consider graphics, customizations, variations, just implement the four basic rules above.


    I also have a special interest in high performance computing, so hope to learn more about performance and scalability by the feedback I get from this node. I've already sought performance advice related to this challenge in Fastest way to lookup a point in a set.

RFC: pragma pragmatic
3 direct replies — Read more / Contribute
by shmem
on Aug 09, 2017 at 03:55

    We all (that's a rough rounded estimate) know about the most important pragma modules - strict and warnings - and maybe also how to turn them on or off, or how to turn on/off a subset of the facilities provided by them. In comparison, few of us know how a pragma really works. I don't either - to know *really* well, I'd have to wade the perl source code, which I won't, for now.

    This I know from the docs, if I haven't misread them: the variable $^H is used for hints to the compiler, e.g. how to behave in respect to refs, subs and vars. The hash %^H is used for hints from the compiler to the interpreter, i.e. perl's runtime. The current state of %^H at compile time is stored in the optree (another obscure thing most perl programmers don't care about, but that's what's getting run), so its state can be retrieved at runtime via (caller($level))[10].

    We could use that to make the scope of imported functions from some arbitrary package purely lexical, even if that package isn't pragma aware. Here's a shot at this:

    Package pragmatic:

    Usage example:

    package Foo; use 5.10.0; require Exporter; @Foo::ISA = qw(Exporter); our @EXPORT = qw(foo); sub foo { say "Foo::foo at line ".(caller)[2] } 1;
    #!/usr/bin/perl use 5.10.0; sub foo { say "main::foo at line ".(caller)[2] } use pragmatic Foo; foo; # line 5 no pragmatic Foo; foo; # line 7 use pragmatic Foo; foo; # line 9 no pragmatic; foo; # line 11 use pragmatic Foo; foo; # line 13 __END__ Foo::foo at line 5 main::foo at line 7 Foo::foo at line 9 main::foo at line 11 Foo::foo at line 13

    A module imported via pragmatic isn't imported into the caller's namespace, but into the package pragmatic::import. Each symbol from that package is inspected, and after inspection, deleted. If the CODE slot is defined, its content is stored in the hash %symbols for this caller and this package. If a symbol of that name is found in the caller, its CODE slot content is saved to the hash %masked. The caller is given a reference to the undefined subroutine of that name in package pragmatic. At runtime, this triggers AUTOLOAD, where the appropriate subroutine is called, depending on whether the pragma is in effect or not.

    This works for exported subroutines only. If a package exports other glob types, they are passed into the caller's namespace, and they aren't managed by pragmatic. I wish there was a way to govern those too.

    To be done yet:

    • a forget(PACKAGE) method which finishes the pragmatic management and stores the stashed subroutines permanently in the caller's namespace
    • ... (fill the blank)

    What do you think? Bad idea? useful? Big delirium? Comments welcome.

    edit: fixed some bugs

    perl -le'print map{pack c,($-++?1:13)+ord}split//,ESEL'
Which internal DSL are there in Perl? (Domain Specific Languages - Part 1)
7 direct replies — Read more / Contribute
by LanX
on Aug 02, 2017 at 22:08
    Taking some definitions from Wikipedia and Martin Fowlers Book: (emphasizes added)

    DSLs are small languages, focused on a particular aspect of a software system. You can't build a whole program with a DSL, but you often use multiple DSLs in a system mainly written in a general purpose language.

    DSLs come in two main forms: external and internal

    An external DSL is a language that's parsed independently of the host general purpose language: good examples include regular expressions and CSS

    Internal DSLs are a particular form of API in a host general purpose language, often referred to as a fluent interface.

    They are represented within the syntax of a general-purpose language. Itís a stylized use of that language for a domain-specific purpose.

    People find DSLs valuable because a well designed DSL can be much easier to program with than a traditional library.

    This improves programmer productivity , which is always valuable. In particular it may also improve communication with domain experts , which is an important tool for tackling one of the hardest problems in software development.

    Now there are some more frequently used examples in Perl which come to mind like SQL and Template languages like in Template::Toolkit2

    [% FOREACH file=files %] [% IF ( matches ='dd/mm/(\d+)') ) %] <a href='#'>[% matches.0 %]</a> [% END %] [% END %]

    Both qualify as are for sure as DSLs.

    They are sub-languages which can be used by "domain experts" without any knowledge of Perl.

    And they are external, because neither SQL nor TT commands are implemented as Perl functions or follow Perl syntax.

    • SQL appears as embedded string inside Perl code is only parsed after leaving Perl thru DBI
    • And TT may be parsed with Perl but is not parsed as Perl.
    So far for external DSLs , but what are good examples for internal DSLs in Perl?

    Well designed traditional modules and classes are sometimes close to represent a sub-language but they still come with a lot of boilerplate.

    For instance an expert in the domain of TCL/TK may (probably?) not care much if the "host" language is Perl or Python or Ruby as long as he can call the commonly known methods. (see for comparison of snippets in various languages).

    But the necessity to constantly repeat an $obj-> or PACK::AGE:: on the left hand side of a command doesn't make it a completely "fluent" approach.

    (On a side note: avoiding to repeat this LHS for method calls seems to be the principal mechanism in Ruby for transforming a simple class to what Rubyists like to call a "DSL", a bunch of function calls inside a block are somehow interpreted as method calls on the same object, hence very similar to the with(obj) {} mechanism in JavaScript - please correct me if not)

    Now, what are examples for internal DSLs in Perl?

    The only widely known one which comes to my mind is CGI::HTML::Functions which used to be part of CGI

    For example, here's one way to make an ordered list:
    print ul( li({-type=>'disc'},['Sneezy','Doc','Sleepy','Happy']) );
    This example will result in HTML output that looks like this:
    <ul> <li type="disc">Sneezy</li> <li type="disc">Doc</li> <li type="disc">Sleepy</li> <li type="disc">Happy</li> </ul>

    Nice but IMHO it could be even more fluent.

    But are there others?

    There is for instance Rex which I suppose was inspired by Ruby's Puppet

    use Rex -feature => ['1.0']; desc "Get Uptime"; task "uptime", sub { say run "uptime"; }

    And I think I could theoretically implement most Assembler languages as Perl code just with some minor changes. I just need to implement ASM-commands as uppercase subs, quote literals and adjust the comment symbol.


    CPX '3' ;# Year starts in March to bypass BCS 'MARCH' ;# leap year problem DEY ;# If Jan or Feb, decrement year MARCH: EOR '$7F' ;# Invert A so carry works right ...
    (original example)

    But there must be more examples of internal DSLs in Perl ...

    Could you please help me to find and classify them?

    Cheers Rolf
    (addicted to the Perl Programming Language and ☆☆☆☆ :)
    Je suis Charlie!

RFC: Confirming module being tested
No replies — Read more | Post response
by RonW
on Jul 31, 2017 at 19:33

    In #p5p finds your lack of failing tests disturbing, there was discussion about Perl no longer including the current directory in @INC and how this would affect modules that load other files. In the referenced post,, the author, Mr Fredric, seems concerned that testing environments, such as Test::More may not be working correctly.

    From that, it occurred to me that it might be wise for tests to confirm that the module being tested is the one the test expects.

    Today, the noderep ticker "reminded" me about this concern, so I wrote a first draft of a version confirmation test:

    use 5.006; use strict; use warnings FATAL => 'all'; use Parse::CPAN::Meta; use File::Spec::Functions qw(catfile); use Test::More tests => 2; BEGIN { diag( "Testing My::Module" ); use_ok( 'My::Module' ); } my $loaded_ver = $My::Module::VERSION; my @metafiles = qw( META.json META.yaml ); my $md; for (@metafiles) { my $mf = catfile('..', $_); next unless (-f $mf); $md = Parse::CPAN::Meta->load_file($mf); next unless (defined $md); if ($md->{version} == $loaded_ver) { pass('version check'); } else { BAIL_OUT('Expected ver ' . $md->{version} . ", got ver $loaded +_ver"); } } BAIL_OUT('Missing META.json and META.yaml') unless (defined $md);

    Edit: Corrected typo in title.

    Update: Use catfile()

Add your 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?

    What's my password?
    Create A New User
    and all is quiet...

    How do I use this? | Other CB clients
    Other Users?
    Others cooling their heels in the Monastery: (7)
    As of 2017-09-25 10:43 GMT
    Find Nodes?
      Voting Booth?
      During the recent solar eclipse, I:

      Results (279 votes). Check out past polls.