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

Seekers of Perl Wisdom

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

If you have a question on how to do something in Perl, or you need a Perl solution to an actual real-life problem, or you're unsure why something you've tried just isn't working... then this section is the place to ask. Post a new question!

However, you might consider asking in the chatterbox first (if you're a registered user). The response time tends to be quicker, and if it turns out that the problem/solutions are too much for the cb to handle, the kind monks will be sure to direct you here.

User Questions
Tearing appart complex spreadsheets ??
No replies — Read more | Post response
by Wiggins
on Dec 20, 2020 at 11:18

    My last posting here was 3yrs, 3 months, 2 days ago; so please be understanding if my question is simply obvious.

    Working with SpreadSheet::Read . Starting with a working sample program and trying to determine how to split the opening of the spreadsheet from subroutines that do the examination and extraction. That is failing.

    #!/usr/bin/perl use strict; use warnings; use 5.010; use Spreadsheet::Read qw(ReadData); my $book = ReadData('simple.xlsx'); say 'A1: ' . $book->[1]{A1}; my @row = Spreadsheet::Read::row($book->[1], 1); for my $i (0 .. $#row) { say 'A' . ($i+1) . ' ' . ($row[$i] // ''); } my @rows = Spreadsheet::Read::rows($book->[1]); foreach my $i (1 .. scalar @rows) { foreach my $j (1 .. scalar @{$rows[$i-1]}) { say chr(64+$i) . " $j " . ($rows[$i-1][$j-1] // ''); } } link : https://stackoverflow.com/questions/19782080/how-to-read-data +-from-xlsx-in-perl [2]

    Inline is simple. I wanted to test a more complex program with subroutines or modules working on the data structure returned by SpreadSheet::Read(). In every case, code that was outside the scope of the SpreadSheet::Read opening the file, the knowledge of what was at that address seemed to be lost. That makes sense.

    #!/usr/bin/perl #https://stackoverflow.com/questions/19782080/how-to-read-data-from-xl +sx-in-perl use strict; use warnings; use 5.010; use Spreadsheet::Read; #my $workbook; # try a global array ref to excel structure -failed ###################################################################### +###### # function input : file in xlsx format with absolute path # function output : prints 1st worksheet content if exist ###################################################################### +###### sub print_xlsx_file{ print ">>print_xlsx_file\n"; my $REFworkbook = shift; my $PageNum; for $PageNum (1..7) { my $worksheet = $REFworkbook->sheet($PageNum); my $max_rows = $worksheet->{'maxrow'}; my $max_cols = $worksheet->{'maxcol'}; print "Stats Page $PageNum ". "$max_rows x $max_cols\n"; } } #===================== MAIN # call above function my $file_path = shift; # passed full path my $workbook = ReadData($file_path,cells => 0 ); my $PageNum=1; if(defined $workbook->[0]{'error'}){ print "Error occurred while processing $file_path:". $workbook->[0]{'error'}."\n"; exit(-1); } print_xlsx_file ($workbook);

    As I write this, I am thinking more that it will have to be a huge linear script.

    It is always better to have seen your target for yourself, rather than depend upon someone else's description.

Here documents in blocks
9 direct replies — Read more / Contribute
by Bod
on Dec 19, 2020 at 11:25

    When I created an account here some five weeks ago, little did I realise just how much varied learning I would receive in such a short time...so I am asking for advice on an issue that has had me scratching my head many times over the years. How best to lay out code when quite a bit of text output is required, such as when dynamically creating a webpage, inside an indented block.

    In the main body of the code I usually use an interpolating heredoc with any runtime variations defined in variables ahead of printing it all out.

    my $login_text = $user_number?'logout':'login'; print<<"END_HTML"; <div> ...part of webpage... <input type="button" name="log" value="$login_text" onClick="doSomethi +ng();"> ...more of webpage... </div> END_HTML
    That works and looks fine for a block of procedural code but I run into difficulties when I want to put something similar into an indented block for any reason. It could be a subroutine that is called to display a largely different page based on the query string or a significant block of content that is only shown under some conditions.
    if (isAdmin($user_number)) { print ...some extra content... }
    Heredocs don't work so well in these circumstances. I am using Perl 5.16 so don't get to use the print<<~"END_HTML"; syntax introduced in Perl 5.26.

    This leaves a few option.
    The one that most of my legacy code has is to simply put every line in a separate print statement

    if (isAdmin($user_number)) { print "<table>\n"; print "<tr>\n"; print "<td class=\"someclass\" style=\"text-align:center\">Some Co +ntent</td>\n"; print "</tr><tr>\n<td class=\"someClass\">Restricted</td>\n" if $u +ser_number == 20; print "</tr>\n"; print "</table>"; }
    Not very pretty and quite difficult to follow as it becomes more involved, especially as more and more HTML gets added over time. So a slight improvement that I used for a short time is with qq to save having to escape the quotation marks.
    print qq[<td class="someclass" style="text-align:center">Some Conte +nt</td>\n]; print qq[</tr><tr>\n<td class="someClass">Restricted</td>\n] if $us +er_number == 20;
    Slightly better - but still not very nice...

    I have tried having a subroutine to strip out leading spaces but this has the disadvantage of always stripping leading spaces even when they are wanted! In this format it also strips out blank lines although this is not too tricky to solve.

    #!/usr/bin/perl use strict; print "Content-type: text/plain\n\n"; print "Test\n\n"; sub indent { my $text = shift; $text =~ s/^\s+//gm; return $text; } if (1) { print indent(<<"END_TEXT"); Here is some test text with plenty of space at the start END_TEXT } exit 0;
    This still requires END_TEXT to be written without an indent.

    Many times I have searched for a solution and found several references to the issue but nothing offering a 'proper' solution. The topic of indentation in some form or another crops up periodically in all sorts of forms including Mandatory indenting which was interesting despite not being directly relevant.

    Other than upgrading to Perl 5.26 or later, is there an elegant solution to laying out code to print a lot of text in an indented block?

Is prove's --ignore-exit flag incomplete or ignored?
1 direct reply — Read more / Contribute
by songmaster
on Dec 18, 2020 at 16:20

    I maintain a non-Perl build system that uses APP::Prove for running tests and displaying the results, with our own code for generating the TAP output from our C/C++ test programs. Those test programs are each exec'd from their own wrapper script (written in Perl) and exit with a non-zero status if any of the tests fail (this exit status is needed for other features of our build/test system). Is there an easy way to suppress the "Dubious" message that gets displayed when a non-zero status is returned, as shown below?

    $ prove --failures --ignore-exit epicsTypesTest.t epicsTypesTest.t .. 1/10 not ok 1 - sizeof(epicsInt8) == 10 epicsTypesTest.t .. Dubious, test returned 1 (wstat 256, 0x100) Failed 1/10 subtests Test Summary Report ------------------- epicsTypesTest.t (Wstat: 256 Tests: 10 Failed: 1) Failed test: 1 Non-zero exit status: 1 Files=1, Tests=10, 0 wallclock secs (0.03 usr + 0.01 sys = 0.04 CPU) Result: FAIL

    Note that I'm already passing the --ignore-exit flag, but it doesn't seem to make any difference to what gets displayed. My App::Prove and TAP::Harness both say they are version 3.4.2. The manpage for prove says:

    --ignore-exit Ignore exit status from test scripts.

    and TAP::Parser's perldoc says:

    "ignore_exit" $parser->ignore_exit(1); Tell the parser to ignore the exit status from the test when determining whether the test passed. Normally tests with non-zero exit status are considered to have failed even if all individual tests passed. In cases where it is not possible to control the exit value of the test script use this option to ignore it.

    Thanks for any insight or hints!

What are the proper names
5 direct replies — Read more / Contribute
by TorontoJim
on Dec 18, 2020 at 10:01
    I'm tyring to reasearch how to do something but I'm not sure what exactly to ask, I keep getting results that are not relevant.

    I will have a webpage with a table (grid, whatever - this is just concept at present). When the page loads, the table will be populated. If I make a change to the data in the table, I can update the server (Perl script) using ajax - as I don't want the user to submit a request that refreshes or navigates away from the page they have open.

    However, if two people have that table open on different computers, the second user won't see my update unless they refresh the display.

    While I could have javascript poll the server (another Perl script) for any changes, is that really the best way to do it? It sems so 1980's. So here is what I need to know:

    What do I need to research, study, investigate, practice, pull my hair out over to achieve this live(ish) updating of data from the server (Perl script)? I'll research it, study it, learn it - I just need to know what it is I'm doing that with.

    Pretty please and thank you.

Having trouble reading in a hash from a referenced array
4 direct replies — Read more / Contribute
by SergioQ
on Dec 18, 2020 at 00:26

    Dear Perl Monks,

    I am running into a wall when I use TMDB's

    my @results = $search->find( id => 'tt0114694', source => 'imdb_id' );

    The result I get back is a hash that comes back in a referenced array. in my case it's just one item returned, which is posted at the bottom. When I read the fifth key in the hash, I get an array. I am assumed that it is also an array of another hash. Obviously it is not, and there is where I am stuck.

    When I use this code, I get the same array for both. If someone can tell me what I am getting wrong, I'd appreciate it so much.

    foreach my $narray (@results){ print $narray->{"movie_results"}; print "\n"; my @newarray = $narray->{"movie_results"}; print $newarray[0]; print "\n";

    This is my output from the original call

    $VAR1 = { 'tv_season_results' => [], 'tv_results' => [], 'person_results' => [], 'tv_episode_results' => [], 'movie_results' => [ { 'adult' => bless( do{\(my $o = 0) +}, 'JSON::PP::Boolean' ), 'vote_average' => '6.8', 'original_title' => 'Tommy Boy', 'vote_count' => 635, 'id' => 11381, 'release_date' => '1995-03-31', 'overview' => 'Party animal Tommy + Callahan is a few cans short of a six-pack. But when the family busi +ness starts tanking, it\'s up to Tommy and number-cruncher Richard Ha +yden to save the day.', 'genre_ids' => [ 35 ], 'title' => 'Tommy Boy', 'video' => $VAR1->{'movie_results +'}[0]{'adult'}, 'poster_path' => '/g32WbO9nbY5ydp +ux5hIoiJkLEQi.jpg', 'original_language' => 'en', 'backdrop_path' => '/bZ4diYf7oyDV +aRYeWG42Oify2mB.jpg', 'popularity' => '13.945' } ] };

getting next word or number after another
5 direct replies — Read more / Contribute
by bigup401
on Dec 17, 2020 at 19:11

    i have found a working solution for my recently https://perlmonks.org/?node_id=11125284

    WORKING #!/usr/bin/perl my $string = " info John 100 - 2000 Kent"; my $word = "info"; $string =~ /$word\s*?(\S+)/; my $next_word = $1; print "The next word after $word is $next_word\n";

    now my problem i cant get the next word or number after john. like this

    NOT WORKING #!/usr/bin/perl my $string = " info John 100 - 2000 Kent"; my $word = "info"; $string =~ /$word\s*?(\S+)/; $string_2 =~ /$string\s*?(\S+)/; my $next_word = $1; my $next_word_2 = $2; print "The next word after $word is $next_word\n"; print "The next word or number after $next_word is $next_word_2\n"; OUTPUT IS The next word after info is John The next word or number after John is

    so am missing next number or word after john

Server-side caching of webpages in Mojolicious
1 direct reply — Read more / Contribute
by rajaman
on Dec 17, 2020 at 16:49

    Dear Perl Monks,

    I am trying to figure out how I can do server-side caching of dynamic webpages that Mojolicious generates in response to webrequests. So that, expensive processing (e.g. on data pulled from a database) done on regenerating the same webpages again is bypassed for subsequent webrequests.

    I was looking for a file-based caching solution for Mojolicious, something like what this module does, but unfortunately the module seems outdated and does not install: Mojolicious::Plugin::Cache. In CGI, such a solution is implemented in CGI::Buffer, and Cache::Cache.

    I found caching support in Mojolicious, but this appears to be client-side caching, as shown below:

    helper 'cache_control.five_minutes' => sub ($c) { $c->res->headers->ca +che_control('public, max-age=300') }; get '/some_older_story' => sub ($c) { $c->cache_control->five_minutes; $c->render(text => 'This one can be cached for a bit.'); }; #ref: https://metacpan.org/pod/distribution/Mojolicious/lib/Mojoliciou +s/Guides/Rendering.pod

    I also tried to use statements as below, but this does not seem to work for me, maybe I am missing something here.

    use Mojolicious::Lite app->renderer->cache->max_keys(100);

    Please advise how to go about.

    Thank you very much!

Qualified package variable access
4 direct replies — Read more / Contribute
by jerryhone
on Dec 17, 2020 at 12:39
    Brothers...any help to identify what I'm doing wrong would be greatly appreciated... I'm putting together some Perl scripts that all connect to an Oracle database. I've put the database connectivity in a library file although I'm leaving each script's specific SQL in the script itself. In my library file (ECClib.pm) I have
    package ECClib; my $dbh; sub initialise(){ . . $dbh = db_connect($dbuser, $dbpasswd, $dbserver); . . )
    That's all fine and dandy, and I seem to get a good database connection. However, if I then try to use $ECClib::dbh in my parent script, it fails. My calling script has
    use ECClib; ECClib::initialise(); my $sql="select InputID from ECCInput order by InputID"; my $sth = $ECClib::dbh->prepare($sql);
    The statement handle assignment fails - debugging shows that $ECClib::dbh is undefined. What am I doing wrong?
How to shuffle this AoA
4 direct replies — Read more / Contribute
by karlgoethebier
on Dec 17, 2020 at 09:30

    Given this data:

    @AoA = ( [ 2, 3, 4, 5 ], [ 2, 3, 4, 5 ], [ 2, 3, 4, 5 ], );

    What i want is something like this:

    @AoA = ( [ 3, 2, 4, 5 ], [ 5, 3, 2, 4 ], [ 2, 5, 4, 3 ], ); # many more

    But not:

    @AoA = ( [ 3, 2, 4, 5 ], [ 4, 3, 2, 5 ], [ 2, 5, 4, 3 ], );

    And not:

    @AoA = ( [ 3, 2, 4, 5 ], [ 5, 3, 2, 4 ], [ 3, 2, 4, 5 ], );

    I have no plan for the moment. And probably even the title of this question is bad.

    Thanks in advance for any advice.

    Update: Thanks to all for the kind and inspiring replies. I guess i need to rethink my specs, right?

    Some words about the background. In the room where i use to record there is too much reverb. By chance i stumbled over this funny video. A DIY "Acoustic Skyline Diffuser". The carpentry work is fubar but the idea is good and the thing looks good. I would use some precut MDF panel and some precut balsa blocks instead and good is. But i wondered how to find a distribution for the blocks.

    Another interesting question is if the proportions of the length of the blocks should be integer or not to reach maximum diffusion. But i'm not an audio engineer. And this problem is far beyond this forum. Another solution would be to buy a pro diffusor and forget about the DIY approach.

    Best regards, Karl

    «The Crux of the Biscuit is the Apostrophe»

    perl -MCrypt::CBC -E 'say Crypt::CBC->new(-key=>'kgb',-cipher=>"Blowfish")->decrypt_hex($ENV{KARL});'Help

How to run a legacy perl version smoothly from perlbrew & Carton
4 direct replies — Read more / Contribute
by chrestomanci
on Dec 17, 2020 at 08:11

    Greetings wise brothers, I seek your advice on how to concurrently access the old and the new.

    I am working on a legacy Perl system that makes heavy use of Storable objects (in a database, traversing the network etc), so it has to run Perl 5.10.1 and no other version. Up until now, it has been run on Ubuntu 10.04 Lucid, which means running a 10 year old Linux distro (with no support) on 10 year old hardware also with no support that could die at any moment.

    I would like to migrate the system to a modern OS (Ubuntu 20.04 Focal) and hardware, while using perlbrew to run the application using the correct Perl version. I have successfully built and installed Perl 5.10.1 and all the necessary libraries using Carton, but I have two problems with this setup that I would like to solve.

    Firstly, to run a Perl script with the correct libraries, I need to put “carton exec” on the front of each script invocation. If you don’t do that then the correct Perl binary runs, but it fails because it cannot find the modules that carton installed.

    How can I arrange things so that just running perl from a shell will do the right thing? (Run Perl 5.10.0 with the carton installed modules available), Perhaps by tweaking PERL5LIB for bash shells, or putting a wrapper script into the path? (note that I don't need to worry about multi user accounts here, all users login as root!)

    Secondly, there are about 200 CGI scripts mostly in Perl, and each with a #!/usr/bin/perl shebang line. How should I configure Apache to call my perlbrew installed version of perl, again with the carton installed modules, preferably without re-writing the shebang line on every script, though if I must do that, then the change needs to be backwards compatible with the old setup.

    Note that this is plain old CGI, not modperl FastCGI or anything like that. I would not object to using an FCGI wrapper if it can be dropped in painlessly, but not if it would require modifications to the scripts, or could be a source of bugs or incompatibilities.

    And before you say it, Yes I am well aware that it would be better to migrate away from Perl Storable. I have seen Elizabeth Mattijsen’s talks on how Booking.com did so at various Perl events. I also know that plain old CGI is no longer considered best practice. My problem is that this is a legacy system, and there is not much time or money available for major system changes, and there is no appetite for anything that could introduce hard to find bugs.


Add your question
Title:
Your question:
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 all is quiet...

    How do I use this? | Other CB clients
    Other Users?
    Others drinking their drinks and smoking their pipes about the Monastery: (1)
    As of 2020-12-20 20:47 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?
      How often do you use taint mode?





      Results (183 votes). Check out past polls.

      Notices?