http://www.perlmonks.org?node_id=479

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
Building ARRAY with grep expression NOT working
3 direct replies — Read more / Contribute
by denting24by7
on Mar 31, 2020 at 16:02

    I am doing something wrong trying to build an array that should contain all jscript extension file names. I am very new to perl. I have this working in bash. I know that the first array has the lines containing the jscript file names. Just can't figure out how to remove just them and put them in an array to sort unique items.

    #!/usr/bin/perl use strict; use warnings; sub main { my @js = (); my @ujs =(); my $file = 'access_log.txt'; open(FH, $file) or die("File $file not found"); while(my $String = <FH>) { if($String =~ '[^/]*\.js') { push(@js,($String)); #print "$String \n"; @ujs = grep {/[^/]*\.js/}, @js; # print @ujs; } } close(FH); foreach (@ujs) { print "$_\n"; } } main();
declaring lexical variables in shortest scope: performance?
7 direct replies — Read more / Contribute
by bliako
on Mar 31, 2020 at 06:22

    Hello lockdown ones,

    Everytime I declare a variable I believe a flop dies in my CPU. Probably because I fell in the C cauldron in my formative years. But now, and in Perl, the paradigm is to "lexicalise" variables within the innermost scope. For example, for:

    my $x; for $x (1,2,3){ print "x=$x\n" }

    perlcritic a.pl says Loop iterator is not lexical at line 6, column 1.  See page 108 of PBP.  (Severity: 5)

    But this pacifies perlcritic:

    for my $x (1,2,3){ print "x=$x\n" }

    But wakes in me primordial fears of will that variable be created 3 times and decrease performance? (for the sake of readability and, perhaps, stability and not introducing subtle bugs). Does anyone know the difference in performance between the two scripts? Even if it is tiny!

    bw, bliako

How install multiple version of perl
4 direct replies — Read more / Contribute
by maria80e
on Mar 31, 2020 at 03:04
    I have the following question in perl.

    1) Is it possible to install multiple version of perl(example perl version: 5.6 and perl version 5.24) in windows system.

    2) How to call the perl file using version. For example, call the new version perl file(5.24) from old version of perl file(5.6).

Grab username from WP Cookie
2 direct replies — Read more / Contribute
by htmanning
on Mar 31, 2020 at 00:45
    Monks,

    I don't know if this is possible, but I need to grab a Wordpress user's username from the cookie once they are logged in. I will pass that to another Perl based part of the site. There are 3 cookies with the username followed by some hash. I'm not having much luck finding a way to read it when I won't know the cookie name ahead of time. Any ideas?

bracket processing
5 direct replies — Read more / Contribute
by rajaman
on Mar 30, 2020 at 21:06

    Hi Monks,

    I am trying to split a string delimited at the longest balanced-bracket, i.e., in a greedy way.

    For example, I want to split the string shown below into two parts: i) 'The use of parentheses.', and ii) '(indicates that the (writer [considered] the {information}) less <important-almost> an afterthought)'.

    While part ii) could be obtained using the code below, I am not sure how to get the remaining part of the string, i.e., part i). I also tried to work with 'Text::Balanced' module but couldn't make it work.

    Thank you for suggestions.

    use Regexp::Common 'RE_ALL'; my $string='The use of parentheses (indicates that the (writer [consid +ered] the {information}) less <important—almost> an afterthought).'; $string =~ RE_balanced(-parens=>'(){}[]<>'} and print "$1\n";
downloading a file on a page with javascript
2 direct replies — Read more / Contribute
by Aldebaran
on Mar 30, 2020 at 17:30

    Hello Monks,

    I thought I would try something easy, namely using perl to download a file, and I have yet to achieve it. The page in question is found on google's public download site, so there isn't a question of permissions: useful utilities.

    I've tried it a few different ways and even another syntax, and what I get with the download is the html for the page itself, which I won't show, but it definitely is the same as when you go to the above site and select "view page source."

    use LWP::Simple; my $url = 'https://code.google.com/archive/p/dotnetperls-controls/down +loads/enable1.txt'; my $file = 'a.txt'; getstore($url, $file);

    Fishing for tips,

for loop less than test ill behaved...
4 direct replies — Read more / Contribute
by JCyow2020
on Mar 30, 2020 at 11:23

    Dear Monks, I have a simple for loop which use the < less than operator in the TEST condition. This works as expected for an assigned scalar, but when I assign the scalar thru a rand call the loop goes 1 iteration beyond the < less than condition to <=. Your wisdom is greatly appreciated. J

    #!/usr/bin/perl # use v5.10; use warnings; #use strict; $data_length = 5; printf "data length = %d\n",$data_length; for($k=0; $k < $data_length; $k++) # the includes up to $data_l +ength - 1 { printf "loop k = %d\n",$k; }# end for() $my_rand5 = rand(5); $data_length = 5 + $my_rand5; printf "data length = %d\n",$data_length; for($k=0; $k < $data_length; $k++) # the test includes $k == $d +ata_length { printf "loop k = %d\n",$k; }# end for()
    Results are as follows: mytest data length = 5 loop k = 0 loop k = 1 loop k = 2 loop k = 3 loop k = 4 <- loop stops at N-1 data length = 9 loop k = 0 loop k = 1 loop k = 2 loop k = 3 loop k = 4 loop k = 5 loop k = 6 loop k = 7 loop k = 8 loop k = 9 <- loop goes 1 iteration too far
i2c bus contention
3 direct replies — Read more / Contribute
by anita2R
on Mar 29, 2020 at 19:04

    Hello,

    I am looking for advice on an approach that I can use to solve this problem:

    I have a Perl script that runs an lcd display over i2c. This runs continuously, reading and displaying new data from a text file. This runs fine and is stable over many months.

    I have a second perl script that reads volts & amps from a device (INA219) that is also connected over i2c. This runs fine when run on a different machine (both Raspberry Pi's).

    But ... when both scripts are run on the same machine, the lcd screen gets garbled and some of the amps/volts data is wrong. It seems that the underlying i2c driver does not handle contention. Both scripts use HiPi::Device::I2C.

    I have overcome the problem by using time slots.

    The amps/volts device can read/write at 0, 5, 10, 15 seconds etc. after each minute and the lcd script can write at (1,2,3) (6,7,8) (11,12,13) seconds etc. after each minute. The data from the amps/volts device is fine and the lcd display is stable using this scheme.

    But this is an ugly fix, so I am looking for alternatives.

    I looked at using a common module with the aim of passing read/write requests from each script to the module, which would then handle them sequentially, so no contention.

    Using two small test scripts and a module I wrote (i2cAccess.pm) I found, perhaps not unexpectedly, that each script loads or uses a separate copy of the module. so there is no common access to the i2c bus. I can post the two scripts and the module if it would be of any use.

    I considered having a lock file that each script accesses, to control access to the i2c bus, but that seems like a lot of overhead, probably worse that my time slot solution.

    I also setup a test using IPC::Shareable

    The aim being to pass the i2c objects, register information etc. to the 'server' program. This failed because, as far as I can tell, Shareable does not support objects. I found a reference to this at https://www.nntp.perl.org/group/perl.poe/2009/12/msg4706.html which says 'Storable can't serialize filehandles'. When adding an i2c object to a shared hash I get 'Can't store GLOB items at ... /IPC/Shareable.pm. Again I can post the test scripts I used if that would be helpful.

    Can the monks suggest an approach to handling this issue.

    Thank you for your consideration.

How can one merge multiple excel files sheet-wise?
1 direct reply — Read more / Contribute
by supriyoch_2008
on Mar 29, 2020 at 09:45

    Hi Perlmonks,

    I am interested in merging multiple (3) excel files sheet-wise i.e. cereal.xls, pulse.xls and fruit.xls,each having two sheets i.e. sheet1 and sheet2, into a single outputfile like result.xls. The sheet1 of result file must contain the contents of sheet1 of 3 input files in sequential rows. Similarly, the sheet2 of result file must contain the contents of sheet2 of 3 input files. While searching the web I have come across a program, given below, to merge excel files but the result file obtained from this program contains the values of sheet1 of 3 input files as sheet1, sheet2 and sheet3; rather the contents of sheet1, sheet2 and sheet3 should be in sheet1 of result.xls. I am using a Windows 7 64-bit pc and comfortable with .xls and not .xlsx. I have tried to get the desired output but failed. I request Perlmonks to suggest me how to sort out this problem.

    #!/usr/bin/perl use warnings; use strict; use Spreadsheet::ParseExcel; use Spreadsheet::WriteExcel; my $parser = Spreadsheet::ParseExcel->new(); #Creating Object to Read +Worksheet my @files = qw/ cereal.xls pulse.xls fruit.xls /; my $write_workbook = new Spreadsheet::WriteExcel('Result.xls'); my $n = 1; foreach my $file (@files) { my $parse_workbook = $parser->parse($file); my $write_worksheet = $write_workbook->add_worksheet("Sheet$n"); if ( !defined $parse_workbook) { die $parser->error(), ".\n"; } for my $parse_worksheet ( $parse_workbook->worksheets() ) { my ( $row_min, $row_max ) = $parse_worksheet->row_range(); my ( $col_min, $col_max ) = $parse_worksheet->col_range(); for my $row ( $row_min .. $row_max ) { for my $col ( $col_min .. $col_max ) { my $cell = $parse_worksheet->get_cell( $row, $col ); next unless $cell; my $cell_value = $cell->value(); my $cell_format = $cell->get_format(); $write_worksheet->write($row, $col, $cell_value); } } } $n++; } print "\n\n ####################################### Result produced\n #######################################\n"; exit;
    The contents of cereal.xls are as follows: Sheet1 No. Name Sugar (g/100g) 1 Wheat 0.3 2 Maize 7.7 3 Rice 0.1 Sheet2 No. Name Protein (g/100g) 1 Wheat 10 2 Maize 7 3 Rice 2.6
    The contents of pulse.xls are as follows: Sheet1 No. Name Sugar (g/100g) 1 Pea 6 2 Chickpea 11 3 Pigeonpea 1.8 Sheet2 No. Name Protein (g/100g) 1 Pea 5 2 Chickpea 8.4 3 Pigeonpea 7.6
    The contents of fruit.xls are as follows: Sheet1 No. Name Sugar (g/100g) 1 Apple 10 2 Pear 10 3 Pineapple 10 Sheet2 No. Name Protein (g/100g) 1 Apple 0.3 2 Pear 0.4 3 Pineapple 0.5
    The desired result.xls file should look like: Sheet1 No. Name Sugar (g/100g) 1 Wheat 0.3 2 Maize 7.7 3 Rice 0.1 1 Pea 6 2 Chickpea 11 3 Pigeonpea 1.8 1 Apple 10 2 Pear 10 3 Pineapple 10
    Sheet2 No. Name Protein (g/100g) 1 Wheat 10 2 Maize 7 3 Rice 2.6 1 Pea 5 2 Chickpea 8.4 3 Pigeonpea 7.6 1 Apple 0.3 2 Pear 0.4 3 Pineapple 0.5
CGI MySQL insert/update special characters
1 direct reply — Read more / Contribute
by Takamoto
on Mar 28, 2020 at 11:13

    Hello monks

    This task should be trivial...but when I insert/update a record in my MySQL database with a value containing special characters, the special characters are not saved. No special message. Why?

    #shortened script #getting pars with CGI my $q = CGI->new(); my $LicenseKey = $q->param('key'); my $UserName = $q->param('user'); my $UserPW = $q->param('pw'); my $dbhServer = DBI->connect("DBI:mysql:$db:$host", $user, $pass); my $sth = $dbhServer->prepare("INSERT INTO Accounts VALUES (?, ?, ?, ? +, ?)"); $sth->execute(undef, $LicenseKey, $UserName, $UserPW, $date) || print +("ERROR EXECUTION: " . $dbhServer->errstr); #same with updating my $sth = $dbhServer->prepare('update Accounts set UserName=?, Passwor +d=? WHERE LicenseKey=?'); $sth->execute($UserName, $UserPW, $LicenseKey)|| print ("ERROR EXECUTI +ON: " . $dbhServer->errstr); $dbhServer->disconnect;

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.