Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW

The Monastery Gates

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

Donations gladly accepted

If you're new here please read PerlMonks FAQ
and Create a new user.

New Questions
Remove SOME new lines
4 direct replies — Read more / Contribute
by RenMcCourtey
on Jun 29, 2016 at 05:06

    Hi, I just hit the issue somewhere I wouldn't expect it. Let's say I want to remove new lines from file, but only some of them. It's obvious to me how to get rid of them all, and it's also what is described everywhere. But while it's easy to replace all Us with Os and all new lines with 'bla', how do I remove new lines from lines starting with U only? I tried following without any success:

    perl -pe 's/\nU/U/g' /tmp/nejms.txt perl -pe 's/^U/U/g' /tmp/nejms.txt
state is the root of evil?
3 direct replies — Read more / Contribute
by basiliscos
on Jun 29, 2016 at 05:04

    Hello dear monks,

    My colleges too-frequently use state feature for aggressive caching. That makes some test problematic, and the functions to be unpure. I'm asking them do not use state, but it seems my arguments aren't strong enough.

    I think I've read some article about state feature misuse, but I can't remember it. If you have a link to some blog, please, share it

    PS. May be I'm not right and state isn't so bad?

    WBR, basiliscos.
RegExp: words excepstions list similar to characters' one.
2 direct replies — Read more / Contribute
by nikolay
on Jun 29, 2016 at 02:23
    Hi. How do i use words excepstions list (like [^qwe|asd]) -- similar to characters' one ([^ghjk])? -- I try to write a script, that would exchange word parts, that contains sign '-', where these parts do not contain (exception) given lists? For example, in the code below
    $z='Web-developer, perl-program, explicit-element, function-call, 2-x +speed.'; print "|$z|\n---\n"; $vrm='(?^ui:(\W)([^(\d|web)]+)-([^(proramm|call)]+)) "1>$1<3>$3< 2> +$2<"'; @bz=split "\t", $vrm; for( $i=0; $i<$#bz; $i+=2 ){ while( $z=~s#$bz[$i]#$bz[$i+1]#g ){ print "|$z|\n"; # <STDIN>; } }

    i want that each part in the 2-word combination, except 'explicit-element', will remain the same, and only 'explicit-element' be turned to 'element explicit' -- because their parts are listed in lists: 'Web-developer' remains the same because its first part 'Web' is in the regular expression, before the sign '-', same for '2-x', whereas 'perl-program' and 'function-call' second parts ('program' and 'call') are listed in the regular expression after sign '-'.

    So, what to do in PERL w/ the exception list for words? Thank you for any advance.

undefined value as filehandle from
2 direct replies — Read more / Contribute
by wanderedinn
on Jun 28, 2016 at 09:46

    I am trying to understand why I am receiving the following error:

    Can't use an undefined value as filehandle reference at /home/geof/httppost/lib/perl5/site_perl/5.8.8/LWP/ line 236

    I have to admit, I don't understand what the code is attempting. Maybe someone can enlighten me? Code with line numbers below:

    233 my $content = ""; 234 open( my $fileb, ">", \$content ); 235 $self->{agent}->setopt( CURLOPT_WRITEDATA, $fileb ); 236 $self->{retcode} = $self->{agent}->perform;

    How is it that the open() above will even work? Can anyone explain to me why I an getting the 'undefined' error? Thanks for any assistance.

randfunc in Config
4 direct replies — Read more / Contribute
by choroba
on Jun 27, 2016 at 05:19
    Dear Monks,

    I got a strange tester failure report for Syntax::Construct. It seems there's a machine with Perl 5.20.2 whose $Config{randfunc} returns drand48 , but my test expects Perl_drand48 . See the relevant perl5200delta:

    > Perl now uses its own internal drand48() implementation on all platforms.

    Corion pointed me to a search for randfunc where the only possibly relevant line is the one from


    I don't understand what the file is used for, so this might be totally unrelated.

    So, my questions are:

    1. Is it OK to have Perl 5.20+ with $Config{randfunc} returning drand48 without the Perl_ prefix? If so, I can check just /drand48/ or use index in the test.
    2. Is there some other method besides using %Config to check that Perl uses its own drand48 function?

    ($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,
Best option for "switch/case" functionality?
7 direct replies — Read more / Contribute
by cheselton
on Jun 27, 2016 at 03:59
    I've been using the use feature qw( switch ) feature, pretty much since in came out in Perl 5.10. As of v5.18 or so, someone with enough clout, decided that the "smartmatch" feature was experimental, and this given/when construct appears to fall into the "smartmatch" category. Normally this isn't an issue, as I'm usually writing one-off scripts that tackle a specific task and/or run on identical platforms -- so the same Perl version all around. I'm currently working on a project that crosses different linux distributions, and therefore different Perl versions. Some (one, actually) before 5.18 and some (most) after (5.20 or so). The older ones run fine; the newer ones complain that the feature is "experimental". One can disable the warnings on the newer perls by using... no warnings "smartmatch::expierimental;...but the older perls don't recognize the pragma and fail to run. So what's the best way to use this case/switch functionality across perl versions without editing my code every time? (Note: I've tried the Switch module, but it doesn't seem to handle regular expressions very well -- especially with nested blocks.) Any help appreciated. TIA
Naming question
1 direct reply — Read more / Contribute
by QSeep
on Jun 27, 2016 at 01:42
    Moose's type-checking philosophy seems to be that we should specify type constraints at the level of an attribute, and check types at the point when an attribute is set. It does not normally check other method parameters. It can, though, e.g. with MooseX::Params::Validate or Moops. This can create performance problems with type-checking aggregates. If you have a large array, and you set a ArrayRefInt to point to it, the constraint must now check every element in the array. What if we had a class that contained an arrayref, and had a type constraint, and methods on that class that are used to add elements would check the type constraint for the added elements? Then when we passed one of these objects in as a Moose attribute, the check for the types of all elements would be constant time.
    package TypedArray; use Moose; has type => ( is => 'ro', isa => 'Moose::Meta::TypeConstraint', required => 1 ); has elems => ( is => 'ro', isa => ArrayRef, default => sub { [] }, ); sub BUILD { my $self = shift; $self->type->assert_valid($_) for @{$self->elems}; } sub elems_push { my $self = shift; $self->type->assert_valid($_) for @_; push @{$self->elems}, @_; } ... more methods and operator overloads ...
    Using overloaded operators, we could make them work much like built-in arrays. To create a new one, you would write, e.g.:
    TypedArray->new(type => Int, elems => [4, 8, -7])
    It would be nice to have a shorthand syntax to create them. We could use BUILDARGS to simplify it to:
    TypedArray->new(Int, 4, 8, -7)
    but it would be nice to get rid of even the `new`. We could make a function, e.g.:
    typedArray Int, 4, 8, -7
    Then we could define a parameterizable type constraint called TypedArrayOf:
    subtype TypedArrayOf as Parameterizable['TypedArray', 'Moose::Meta::TypeConstraint' +], where { my ($typed_array, $type) = @_; $typed_array->type->is_a_type_of($type) }, message { my ($typed_array, $type) = @_; return "expected TypedArrayOf[$type], found TypedArrayOf[@ +{[$typed_array->type]}]" };
    Unfortunately, we could not use the class name for the type constraint, because this is not a class constraint, and we do not want to conflict with the class constraint. So I chose a compromise by appending the word 'Of' to the name. Instead of having a single TypedArray class, another option would be to create a new class on the fly for each possible type parameter. We could use a parameterized role to build them, using Class::MOP to generate the new classes on demand. Then TypedArray would become a function, taking a single parameter that is an arrayref with the contained type. E.g.,
    would look up the Int type in a global cache, and if not found, would generate a new TypedArray class, parameterized on Int. That class would constrain all elements to be Ints. This could get expensive if we end up creating a lot of classes. What do folks think of the naming here? Can we be more succinct? More consistent? How can we avoid naming conflicts between 1) the class without a type parameter, 2) the class with a type parameter, 3) a constructor function without a type paramter, 4) a constructor function with a type parameter, 5) the type constraint without a parameter, 6) the type constraint with a parameter. What is the most "Moosey" approach?
Only showing part of POD when not rendered as HTML
1 direct reply — Read more / Contribute
by perlancar
on Jun 26, 2016 at 06:51

    I have some text tables on my module POD, e.g. Bencher::Scenario::Accessors::Get.

    I'm thinking of showing a sortable HTML table (which contains some JavaScript) instead when the POD is rendered to HTML as in sites like This will be done using =begin HTML ... =end HTML POD commands.

    I'd also like that the text table is not displayed on HTML output, so the user is not seeing two tables (one text and one HTML). Any idea? Two of mine so far:

    1) in the =begin HTML ... =end HTML snippet, hide the text table DOM element using some CSS or JS. But this will depend on how the POD is rendered to HTML, i.e. I can make it work on but it might not work on other sites like say which might render the HTML differently.

    2) put the text table in =begin man ... =end man *and* =begin text ... =end text. But this feels dirty. What about other output formats?

Clever optimisation: by design or luck?
3 direct replies — Read more / Contribute
by BrowserUk
on Jun 24, 2016 at 19:38

    I'm a big fan of 'constant functions' and pragmas (constant & enum) that create them for reasons, the knowledge of which seems to have become lost to the current generation of perlers; and is completely lost on the authors and proponents of the newer modules, like Readonly, that are billed as (very poor) substitutes for them.

    I was working on my answer to syphilis' question in Re^3: unintentional conversion of signaling NaN to quiet NaN and thought to make a SNaN constant; and did, but I was testing it when I discovered something that is either very clever design; or simply a really cool bit of luck. I'm not sure which?

    I implemented the constant very simply as:

    use constant SNaN => unpack 'd',pack 'Q', 0x7ff0000000000001;

    But how could I be sure that it was being properly reduced to a constant value?

    With an integer constant it is quite simple with B::Deparse:

    C:\test>perl -MO=Deparse -le"use enum qw[false true]; print 'fred' if +false; print 'bill' if true" use enum ('false', 'true'); '???'; print 'bill'; -e syntax OK

    Sure enough, true & false have been defined as constant subs producing 1 & 0 respectively, and Perl has used their constant nature to optimise the code so that the entire print 'fred' if false; part of the program has been optimised away as it can never be executed. Likewise, the ... if true; has been optimised away since it can never be false. (Try that with Readonly :)

    This also works with expressions that yield a constant value:

    C:\test>perl -MO=Deparse -le"sub PI(){ 2*atan2(1,0) }; print PI; if( P +I == PI ) { print 'Here'; }" BEGIN { $/ = "\n"; $\ = "\n"; } sub PI () { 3.1415926535897931 } print 3.1415926535897931; do { print 'Here' }; -e syntax OK

    The expression has been evaluated to a constant, a constant function created. And notably, the optimiser recognises that constant == constant is always(*) true, and the if condition has been optimised away.

    But this one really impressed me;

    C:\test>perl -MO=Deparse -le"use constant SNaN => unpack'd', pack'Q',0 +x7ff0000000000001; print SNaN; if( SNaN != SNaN ) { print 'here'; }" BEGIN { $/ = "\n"; $\ = "\n"; } use constant ('SNaN', unpack('d', pack('Q', 9218868437227405313))); print unpack("F", pack("h*", "1000000000000ff7")); do { print 'here' }; -e syntax OK C:\test>perl -MO=Deparse -le"use constant SNaN => unpack'd', pack'Q', +0x7ff0000000000001; print SNaN; if( SNaN == SNaN ) { print 'here'; }" BEGIN { $/ = "\n"; $\ = "\n"; } use constant ('SNaN', unpack('d', pack('Q', 9218868437227405313))); print unpack("F", pack("h*", "1000000000000ff7")); '???'; -e syntax OK

    At first glance some will be surprised that it is the body of the equal (==) comparison that has been optimised away completely and the body of the unequal (!=) comparison that has been left behind but that isn't what impressed me. What did is this:

    1. At first I was a little disappointed to see that the unpack,pack, 'constant string' hadn't been reduced to a simple floating point constant the way 2*atan(1,0) above was.

      But then I realised that there isn't a floating point constant that can be embedded as source code that will translate to SNAN. That's why I need to use pack/unpack to define it.

    2. But the real surprise was that the optimiser recognised that SNaN == SNaN is the (*)one time when constant == constant is false!

      And then performs the appropriate optimisation; the inverse to the normal case.

    So I wonder, is this special cased in the interpreter? A product of thorough, good design? Or simply fortuitous?

    I did start to explore the source, but quickly got lost. Anyone know?

    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority". I knew I was on the right track :)
    In the absence of evidence, opinion is indistinguishable from prejudice. Not understood.
Handshake mechanism in perl
2 direct replies — Read more / Contribute
by t-rex
on Jun 24, 2016 at 01:51

    i am working for a project where i have implemented concurrent server , now i need to take back logs 9 in a hand shake mechanism without except module) the flow of my code is : { #try connecting to the server socket System(run or die “couldn’t run perl” If (fails) { Transfer files on server machine via scp Run Socket established Try connecting again to the server socket from client, (this time it w +ill connect) }
    My doubt now is how do I know whether everything is running , this code is a part of one big automation so I can’t use std libraries, maybe a log file , I know how to open and write to a file but a robust handshake mechanism is what I desire , anyone has any ideas for the same.

using File::Find to find recently-installed modules
2 direct replies — Read more / Contribute
by Datz_cozee75
on Jun 24, 2016 at 01:11

    Hello Monks,

    I'm working through the exercises in the alpaca book, to wit where the castaways have specified a local::lib and now seek to write a script that gives useful time data associated with these files. My needs are not exactly what the book calls for in any one exercise but range over several, so I used File::Find for the first time instead of relying on windows explorer to tell me where and what things are. (Uggh.)

    In the last couple weeks, I've torn out and replaced an overgrown perl install with this machine, so I wanted to pay some attention to make this install a bit more robust, and consequently have strawberry perl. I had a false start on local::lib, which I hope won't matter in the scheme of things, which I only state so that no one could say "why didn't you tell us you had a screwy, abortive, previous attempt at creating a local::lib?" It may matter, may not. That's part of what I'm learning. Here's what I have now:

    use strict; use warnings; use utf8; use 5.014; use File::Find; my @directories_to_search = ('.', 'C:\Users\Fred\Desktop'); my @files; find( \&find_module, @directories_to_search ); sub find_module { if ( $_ =~ m/.pm$/ ) { my $name = $File::Find::name; push( @files, $name ); } } for my $file (@files) { my $mtime = (stat $file)[9]; # mtime via slice my $when = localtime $mtime; print "$when: $file\n"; }


    ... Thu Apr 30 10:24:40 2015: ./alpaca/template_stuff/ Sun Jun 5 14:32:45 2016: ./alpaca/template_stuff/ Sun Jun 5 14:08:18 2016: ./alpaca/template_stuff/ Thu Apr 30 10:24:40 2015: ./alpaca/template_stuff/ Wed Jun 9 08:59:19 2010: ./perl5/lib/perl5/HTML/ Wed Jun 9 08:24:01 2010: ./perl5/lib/perl5/HTML/ Wed Jun 9 13:56:58 2010: ./perl5/lib/perl5/HTML/ Wed Jun 9 16:17:31 2010: ./perl5/lib/perl5/HTML/ Thu Feb 15 07:35:15 2007: ./perl5/lib/perl5/HTML/ Thu May 21 09:22:21 2015: ./perl5/lib/perl5/HTML/ Mon Nov 1 07:04:16 2010: ./perl5/lib/perl5/Prompt/ Wed Jun 24 04:07:26 2009: ./perl5/lib/perl5/WWW/Mechanize/

    It appears that cpan modules are getting stored in a place that seems to have 'perl5' in it twice. Hope that's okay. Scripts are able to find these so far. Otherwise, I see that, unlike the professor, mtime is not what I'm looking for, as the time I'm interested in is when they got saved to this locale. Is there a perl way to make sure I own these? (The dot is 'Documents', so I would think so indeed.)

    My quest for a "born-on" timestamp continued with reading up on stat, so I worked up versions of the same material using atime and ctime. I don't think I see the difference between the two, so I wonder which one works better as a "born-on" date in this context:

    use strict; use warnings; use utf8; use 5.014; use File::Find; my @directories_to_search = ('.', 'C:\Users\Fred\Desktop'); my @files; find( \&find_module, @directories_to_search ); my @time =localtime; say "local time is @time"; sub find_module { if ( $_ =~ m/.pm$/ ) { my $name = $File::Find::name; push( @files, $name ); } } for my $file (@files) { my $atime = (stat $file)[8]; # atime via slice my $when = localtime $atime; print "$when: $file\n"; }

    atime output:

    local time is 13 44 19 23 5 116 4 174 1 Mon Jun 13 19:12:19 2016: ./alpaca/template_stuff/ Mon Jun 13 19:12:19 2016: ./alpaca/template_stuff/ Mon Jun 13 19:12:19 2016: ./alpaca/template_stuff/ Mon Jun 13 19:12:19 2016: ./alpaca/template_stuff/ ... Wed Jun 22 22:09:13 2016: ./perl5/lib/perl5/HTML/ Wed Jun 22 22:09:13 2016: ./perl5/lib/perl5/HTML/ Wed Jun 22 22:09:13 2016: ./perl5/lib/perl5/HTML/ Wed Jun 22 22:09:13 2016: ./perl5/lib/perl5/HTML/ Wed Jun 22 22:07:17 2016: ./perl5/lib/perl5/HTML/ Wed Jun 22 22:08:24 2016: ./perl5/lib/perl5/HTML/ Wed Jun 22 22:12:21 2016: ./perl5/lib/perl5/Prompt/ Wed Jun 22 22:06:40 2016: ./perl5/lib/perl5/WWW/Mechanize/

    This has the useful information I need, and seems the same on inspection as the same script with the change of

     my $ctime = (stat $file)[10];  

    My intent is to make comparisons of time values part of the search criteria. I found many of these values astonishing and unexpected compared to the reading. Again my final question for moving forward is whether atime or ctime would serve as a better born-on date. Thank you for your comment.

Mocking a method defined in a Moo Role
2 direct replies — Read more / Contribute
by PopeFelix
on Jun 23, 2016 at 13:44

    I have a method, let's call it "foo" defined in a Moo Role.

    package 'MyRole'; use Moo::Role; sub foo { return 'blah'; }

    In a consuming class, I have some behavior implemented in an "around" modifier:

    package MyClass; use Moo; with 'MyRole'; around foo => sub { my ($self, $orig) = @_; if ($self->$orig eq 'baz') { return 'bak'; } return $self->$orig; }

    I would like to test this behavior, but I can't figure out how to mock MyRole::foo. If I mock MyClass::foo, the around() modifier isn't called. How do I test this around() behavior?

    Here's what I'm trying:

    use MyClass; use Test::Most; use Test::MockModule; my $mock = Test::MockModule->new('MyRole'); $mock->mock('foo' => sub { return 'baz' }); my $obj = MyClass->new; # Does not work is $obj->foo, 'bak', 'Foo is what it oughtta be';
New Meditations
PWM on raspberrypi with bcm2835
1 direct reply — Read more / Contribute
by martell
on Jun 25, 2016 at 13:14

    Dear Monks

    I thought I share this small Perl program demonstrating the possibility to do PWM (Pulse Wide Modulation) on Raspberry Pi in order to control the intensity of a led. This is a common introduction example to try for people learning about electronics on Raspberry Pi. Well documented examples for python exists, but not for Perl.

    The reason I share this here, is that the current CPAN module Device::BCM2835 doesn't define the necessary function to do this (that I see). So it took me some tinkering before I could control the PWM from Perl. Novice users of Perl may find this example code the thing they need.

    The solution I apply is the use of the Inline::C module to call some small wrapper functions I wrote in C around an existing C example I found on the internet. They call in turn the bcm2835 functions needed. This is tested on a raspberry pi B, revision 2 unit, using a single led and a single resistor.

    Be aware that on later versions of Raspberry Pi the GPIO pin layout is different and you have to use other constants in the functions calls in the C code. So YMMV, but enough documentation exists on the internet to figure out the correct values.

    This code assumes you have installed the Inline::C module, Time::HiRes module, and the bcm2835 C library on your device. See Device::BCM2835 module for the appropriate links to the C library. It is not installed by default. Run as root on Raspberry Pi because you need to have access to some low level functions.

    Today I'm not proficient in XSLoader to update the Device::BCM2835 module itself, but if I have some spare time, I will look into it. Would be a nice additional skill to master.

    Any thoughts or comments appreciated.


Azure remote desktop / Issues acessing network drives
1 direct reply — Read more / Contribute
by talexb
on Jun 23, 2016 at 10:10

    My work currently involves doing ETL (data-munging) using Perl. Because some of the data may have private information (PII), I'm doing my work on a remote desktop, which at this organization is Azure (Windows). It's not really my choice of platform -- but at least I'm able to use the excellent git-bash package to get (more or less) back to a Linux type command line.

    The issue I'm having is that transferring files from my volume to the volume where my output is carried on to the next step is unreliable, and I'm wondering if anyone else has come across the same challenge. I also want to check the existing files, as I append a version number to the end of my files so that new files don't overwrite existing files.

    • Copying files using File Explorer works, but sometimes a transfer will stall at 99%, at which point I may lose my connectivity to the remote desktop. That isn't a bad thing, although it irritatingly loses the network path in the destination folder, and I have to drill down through seven layers of directories to get back to where I was to check that my copy succeeded before disconnecting.
    • Copying via the command line (you knew that was coming next), while logical, also appears to be hilariously slow. A file that might get copied in 15-20 seconds using Explorer takes 15-20 minutes from the command line. I have no idea why, as it should be going from one network drive to another.

    The solution I've finally hit on (this is my work in progress) is to use chdir to go into the directory in question, and then glob to get a list of the files. It still takes ten seconds to get a list of files, but I guess that's the best I can do right now.

    Thoughts, comments, ideas are welcome. Thanks!

    Alex / talexb / Toronto

    Thanks PJ. We owe you so much. Groklaw -- RIP -- 2003 to 2013.

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (9)
As of 2016-06-29 17:26 GMT
Find Nodes?
    Voting Booth?
    My preferred method of making French fries (chips) is in a ...

    Results (385 votes). Check out past polls.