Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

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
hash question
3 direct replies — Read more / Contribute
by duyet
on May 26, 2016 at 06:46
    I've been working with hash for a while now, but there is something i really don't understand.
    my $hash = {}; do_something( $hash ); print Dumper( $hash ); sub do_something { my $hash = shift; $hash = { a => 'alpha', b => 'beta', }; print Dumper( $hash ); }
    when exectuted:
    { 'a' => 'alpha', 'b' => 'beta' } {}
    but if using:
    do_something_else( $hash ); print Dumper( $hash ); sub do_something_else { my $hash = shift; $hash->{g} = 'gamma'; $hash->{d} = 'delta'; print Dumper( $hash ); }
    it shows:
    { 'd' => 'delta', 'g' => 'gamma' } { 'd' => 'delta', 'g' => 'gamma' }
    To me the initialization of $hash is the same in both subs, but apparently it is not. It's probably something very trivial, but i just miss it. Would you please explain why? TIA.
Code coverage of forked code
1 direct reply — Read more / Contribute
by britterm
on May 25, 2016 at 11:46
    Hi monks,

    I have a module which forks several times to set up a few workers. I'm using Test::More and Devel::Cover to do unit testing of my code and generate code coverage. I have unit tests that stress the workers, but the coverage report shows that the forked code didn't execute even though it did.

    I considered putting the child code into separate functions that can be tested independently of forking, but the code relies on piped handles to communicate with the parent, which AFAIK do not function without forking (can't write/read to a pipe in the same process). I would have to do a significant amount of coding in my unit tests to attempt to work around this, and I'm looking for a more straightforward solution if there is one.

    Does anyone know how to configure Devel::Cover to detect coverage in the child process when the program forks? Is this even possible? (perhaps with a different coverage tool?)

    Thanks in advance,
    Brian
Finding file level lexical variables
1 direct reply — Read more / Contribute
by johndeighan
on May 25, 2016 at 11:35
    Our mod_perl application is sometimes running out of memory. So, I want to create a function to track down all variables outside of functions and check their memory usage using Devel::Size. I'm using Package::Stash to find all package variables (declared using 'our'), but now I want to also find all lexical variables (declared with 'my') which are at the file, i.e. top, level in all packages. I know about PadWalker but don't know how to use it - or anything else - to find and get the memory used by these top level lexical variables.
Collaborate on a module
4 direct replies — Read more / Contribute
by ASeekerOfWisdom
on May 24, 2016 at 10:17

    So sometime ago I adopted a module. The original author had not updated this module for a while and When I spoke to him he was glad I was taking this module over. So after some time I fixed it. Now that module is ready for a release to CPAN.

    So my question is how do I release this module on CAPN? Do I ask the author to release it or Do I release it under my pause ID? (I don't want to take the credit form the original author for doing a lot of the foundation work) This is my first time doing something like this so sorry if this sounds stupid.
Progress count for save_content in WWW::Mechanize
2 direct replies — Read more / Contribute
by perlmad
on May 23, 2016 at 09:48

    Hi Folks

    I am using www::mechanize module to download a file from website and i could not find how long it's take to complete so i need a progress amount for downloading status, my code is shown below

    $mech->save_content($filename,":content_cb" => \&callback); sub callback { my( $data, $response, $proto ) = @_; $progress_amount+= length($data); my $size = $response->header('Content-Length'); print floor(($progress_amount/$size)*100),"% downloaded\n"; # +print percent downloaded }

    It is not working

    Any Idea...

[SOLVED]:Upgrading Perl 5.8 program to 5.22
3 direct replies — Read more / Contribute
by $h4X4_|=73}{
on May 23, 2016 at 06:58

    I would like a Perl program I made years ago to run the latest version of Perl 5.22. But the biggest problem I face with this task is the size of the program. The only way I see this happening is if I rebuild the hole framework from scratch under 5.22 while trying to recycle and convert some methods.

    There is no other reason I can see why i need to upgrade other than the fact that the program is stuck at Perl 5.8 and to upgrade to 5.22 would need a major overhaul to the hole framework.

    Are there any advantages of using the latest Perl version that I missed?

    The lesson was... Don't use Exporter in a file you have named "exporter" to keep your variables in scope. But you can use Exporter in a file called "foo" and it will work fine.
Plack/PSGI Application Deployment
3 direct replies — Read more / Contribute
by expandstudios
on May 22, 2016 at 21:45

    Hey guys, I am in the process of porting an old CGI based web app to PSGI.

    I am just seeking some clarification about how to best configure my environment for hot deployment / CI.

    Environment (so far)

    • CentOS 6.7
    • Perlbrew
    • PSGI WebApp
    • Starman
    • Server::Starter (??)

    Here is what I want to be able to do:

    1. Have the server start on boot (CentOS Service possibly?)
    2. Deploy code to host (most likely using whiskey_disk or possibly git hooks)
    3. Gracefully restart server

    Where I am really looking for guidance is how to best configure the server/application on the CentOS machine so that it will start on boot and can easily be managed (start/stop/graceful restart).

    Once I have that in place I can automate my deployment fairly easily using various tools.

    I just can't get my head around how to use Server::Starter properly in this instance.

    Thanks in advance! Russ

Are you using Perl 6 in production?
2 direct replies — Read more / Contribute
by stevieb
on May 22, 2016 at 16:22

    I've dabbled with it here-and-there (the last real tests I've done were about two years ago). Perl 5 is my favourite language, and I now program in Python professionally.

    I dabbled in p6 prior to learning Python, and there are some obvious similarities, but p6 still has a perl-esque feel.

    It's a slow day here, so I thought I'd ask if anyone here is using p6 in any real-world prod situations, and if so, for what.

    As an aside, I'm curious to know how p6 handles external modules. Yes, I can go do homework, but I thought I'd ask in order to get some feedback here so many people can be apprised. It doesn't appear as though the CPAN handles p6 modules.

    -stevieb

Marshalling Data
2 direct replies — Read more / Contribute
by BillKSmith
on May 21, 2016 at 11:09

    I know that I asked much the same question marshalling data about three years ago. Your answers convinced me that I was not yet ready for this topic. I recently came across my old work and decided to try again.

    The book “Intermediate Perl” ISBN 9781449393090 has a section on marshalling data. In that section, it outlines how to create a pair of arrays each of which contains reference to the other, save these arrays to a file with Data::Dumper, and later, restore them by running eval on the contents of the file. The following code is my attempt to implement and test that example. In order to minimize the number of files in my post, I save the data to a memory file and restore to a separate package in the same script. I have two tests. Each tests that the address portion of one of the references is indeed the address of the other array. The pair of tests is run on the original arrays to validate the tests. The same pair of test is then run on the restored arrays. One of theses tests fails. This convinces me that the arrays are not restored correctly. My question is “why?”. I am not yet interested in any other way to save those arrays. (That is covered later in the same chapter.)

    use strict; use warnings; package main{ use Data::Dumper; our $marshall_data = \do{my $file_simulator}; my @data1 = qw(one won); my @data2 = qw(two too to); push @data2, \@data1; # Add recursive elemen +ts push @data1, \@data2; open my $FH, '>', $marshall_data; print {$FH} Data::Dumper->Dump( # Marshall the data [ \@data1, \@data2 ], [qw(*data1 *data2)] ); close $FH; Testing::recursive_data(\@data1, \@data2); # Both tests pass } package Other{ my @data1; my @data2; open my $FH, '<', $main::marshall_data; my $string = do {local $/ = undef; <$FH>}; # Slurp the string close $FH; # print $string, "\n"; eval $string; # Restore content of a +rrays die "Marshalling Failed: $@\n" if $@; Testing::recursive_data(\@data1, \@data2); # Second test fails } package Testing{ use Scalar::Util qw( refaddr ); use Test::Simple tests => 4; sub recursive_data{ my ($data1_ref, $data2_ref) = @_; ok( refaddr($data1_ref) == refaddr($data2_ref->[3]), '$data2[3] refers to @data1' ); ok( refaddr($data2_ref) == refaddr($data1_ref->[2]), '$data1[2] refers to @data2' ); } }

    Note: Contents of the file are exactly as specified in the book.

    @data1 = ( 'one', 'won', [ 'two', 'too', 'to', \@data1 ] ); @data2 = @{$data1[2]};
    Bill
Is validation of all subroutine arguments overkill?
6 direct replies — Read more / Contribute
by nysus
on May 21, 2016 at 03:36

    I've been learning test-driven development over the last couple of days. The process has gotten me to become much more careful with my code...but perhaps too careful.

    I was always the type of programmer that rarely validated arguments passed to subroutines. If an argument was passed that was not the expected format, the program would behave unexpectedly or crash and then I'd deal with it. With test-driven development, I'm finding myself writing tests to ensure a subroutine returns the appropriate error message if a passed argument is not what the subroutine expects.

    This is certainly a lot more work. Though I'm sure it makes my code is more robust, I'm wondering at what cost. I'm not writing code for banking institutions or space programs, after all.

    So I'm wondering how other Monks approach argument validation. Is this something you do diligently and is considered to be best practice? Do you think it's worth the time to write tests to ensure subroutines handle bad arguments? Are you using modules like Param::Validate to check subroutine arguments? Any other thoughts on argument validation you'd like to share?

    $PM = "Perl Monk's";
    $MCF = "Most Clueless Friar Abbot Bishop Pontiff Deacon Curate";
    $nysus = $PM . ' ' . $MCF;
    Click here if you love Perl Monks

Testing private methods a no-no?
3 direct replies — Read more / Contribute
by nysus
on May 20, 2016 at 10:22

    I'm new to testing. I've got a test that uses a call to a private method like so:

    # Check that module loads data my $xyz_events = $checker->_get_event_data('arg'); my $is_hash_ref = ref $xyz_events eq 'HASH'; is $is_hash_ref, 1, 'returns a hash ref';

    I'm thinking it's OK to break the rules a bit since I'm just running tests. It also seems like it makes writing tests easier by testing small components of the module. But I worry it's a sign that I'm going about testing in the wrong way. What is the opinion of the wiser Monks about this?

    $PM = "Perl Monk's";
    $MCF = "Most Clueless Friar Abbot Bishop Pontiff Deacon Curate";
    $nysus = $PM . ' ' . $MCF;
    Click here if you love Perl Monks

DBI::CSV using a variable to request columns
3 direct replies — Read more / Contribute
by Sandy_Bio_Perl
on May 20, 2016 at 10:21

    Hello Monks. I would like to use a variable "$columns" to describe the columns I wish to extract. Perl will not allow me to store, for example, $column = "sid = $row->{sid}"; because it demands that I declare $row

    I have pasted the troublesome code below. Thank you, in advance for your perls!

    use strict; use warnings; use Text::CSV; use DBI; use Data::Dumper; # Connect to the database, (the directory containing our csv file(s)) my $dbh = DBI->connect ("dbi:CSV:", undef, undef, { f_dir => ".", f_ext => ".csv", f_encoding => "utf-8", RaiseError => 1, }) or die $DBI::errstr; # Output using sql query my $query = (qq(select * from newCsv.csv WHERE gender ='male' AND geno +type ='a' )); # my $columns = "sid = $row->{sid} \tgender = $row->{gender}\n"; # per +l is seeking declaration of $row my $queryResult; my $sth = $dbh->prepare($query); $sth->execute; while (my $row = $sth->fetchrow_hashref) { my $col= "sid = $row->{sid} \tgender = $row->{gender}\n"; # cannot ch +ange this to my $col=$columns $queryResult = $queryResult.$col; } $sth->finish(); $dbh->disconnect(); print "Result \n\n$queryResult";
New Cool Uses for Perl
i2c attached LCD Character Display for a Raspberry Pi
1 direct reply — Read more / Contribute
by anita2R
on May 24, 2016 at 12:28

    I was unable to find a Perl script to make my SainSmart LCD character display with i2c 'backpack' work from my Raspberry Pi.

    Code for using these devices is available mainly for the Arduino. There is also code in C and python, but I could not find a simple working example in Perl. There is a module for an HTBackpackV2 (HiPi::Interface::HTBackpackV2), but I wasn't able to get this working with the SainSmart LCD.

    I found a python script written by Matt Hawkins here: https://bitbucket.org/MattHawkinsUK/rpispy-misc/raw/master/python/lcd_i2c.py and I used his python script as the basis for my Perl Script - thanks Matt.

    This script only provides basic display functionality and is run by calling it with two parameters, -s a string of text to display and -l the line number to display the text on. Hopefully it will provide both a way for others to get one of these LCD's working as well as provide the basis for more comprehensive implementations. The subroutines writeByte and sendByte are the key ones, together with the initialization sequence in the init subroutine.

    The script must be run as root to set up the i2c object, but drops back to the regular user immediately after - enter your user name and user group in the two variables $user and $group which you will find at lines 39 & 40.

    When called with no text and no line parameter the LCD initialization code is run.

    After the code I have added some explanation about the way the data is transferred from the backpack to the LCD, including the transition from the power-up 8-bit mode to 4-bit mode. It took me some time to get my head round this!

    In addition to -l 1 & -l 2 for the two lines, -l 50 & -l 51 turn the display off and back on. When the display is turned off with -l 50, the data remains in the LCD's DDRAM memory and the previous text will be displayed by -l 51 (a simple flashing display can be implemented)

    If no line number is given, the text is printed on line 1 and overflows to line 2 if required. All existing text is cleared.

    Examples (run as root/sudo):


    Code for a Raspberry Pi with SainSmart 2 line, 16 character LCD display with i2c backpack at 0x3f, attached to the Pi's default i2c pins.

    Mode of operation & initialization

New Obfuscated Code
Having fun with ambiguity
No replies — Read more | Post response
by trizen
on May 23, 2016 at 14:30
    print $$ /0; # a legit division by zero ^....some.....^ ^....black....^ ^....magic....^ |(?{m{(?{(("\[\[ \)\.\\\|\`\]\[\[ \{\[\.\@\/\(\^\. \[\{\;\\\,\[\@\: \?\+\^\)\("=~s{[ \s]}<>rg)^("\+\) \@\@\(\^\*\(\(\/ \[\:\@\/\[\@\;\\ \{\+\^\.\@\{\(\[ \\\@\;\[\"\""=~s <\s>()gr))})},s[ ]<$^R>seexi})|&: ^....hugs....^ ^.....&......^ ^...kisses...^ // //xo//xo//xo//xo//xo//xo//xo// //
New Monk Discussion
Put the formatting information above the posting text box?
3 direct replies — Read more / Contribute
by stevieb
on May 20, 2016 at 19:02

    I'm thinking primarily for SoPW (but I assume a change would affect all posting pages), does anyone think that it would have a positive effect if we had the formatting information (it's rather brief relative to having to scroll to the bottom of the page anyway) *above* the text box?

    I'm not really a statistical type person so this isn't a request for action, but a request for feedback.

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 examining the Monastery: (5)
As of 2016-05-26 22:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?