Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Seekers of Perl Wisdom

( [id://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.

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.

Post a new question!

User Questions
Push to array as part of Struct
4 direct replies — Read more / Contribute
by Miq19
on Sep 10, 2024 at 09:56
    I have a data structure like
    my @scales; struct( Scale => { name => '$', offset => '$', foo => '$', index => '$', chords => '@', notes => '@' });
    I found no way on how to push data to the @chords and @notes arrays of a record with that structure. I tried f.i.
    my $sref = $scales[$scale]->chords; push @{$sref}, $found_chord . ';' . $c[1];
    which runs without an issue, but leaves the array empty. If I use Dumper to show the data I get like
    ... bless( { 'Scale::index' => '8', 'Scale::notes' => [], 'Scale::name' => 'Major Bebop Eb', 'Scale::chords' => [], 'Scale::foo' => 'E61100', 'Scale::offset' => undef }, 'Scale' ), bless( { 'Scale::offset' => undef, 'Scale::foo' => 'E61100', 'Scale::chords' => [], 'Scale::name' => 'Major Bebop F', 'Scale::notes' => [], 'Scale::index' => '9' }, 'Scale' ), ...
    which looks like there are just empty arrays in that struct. How is the correct push syntax here?
$x = `cat big_file` seg faults
3 direct replies — Read more / Contribute
by Danny
on Sep 09, 2024 at 18:15
    file1 has size 2147483648 (2**31)
    file2 has size 2147483647 (2**31-1)
    perl -we 'my $x = `cat file1`' # seg faults
    perl -we 'my @x = `cat file1`' # works fine
    perl -we 'my $x = `cat file2`' # works fine
    perl -we 'my $x = `cat file2`; $x .= `cat file2`' # works fine
    So it seems that in scalar context if the output of the command in backticks is greater than 2**31-1 then it segfaults. It seems the backticks use some buffer that has a size limit. The results were the same on 64 bit linux and cygwin.

    Update: Curiously if I do:

    perl -we 'my $x = `cat file2 file2`'
    I get a
    Out of memory in perl:util:safesysmalloc (cygwin perl 5.40)
    or
    Out of memory! (linux perl 5.38)
    instead of a
    Segmentation fault

Mechanize - Bad File descriptor
3 direct replies — Read more / Contribute
by Marshall
on Sep 09, 2024 at 17:05
    I am having trouble connecting to an HTTPS site with Mechanize. I can connect to other HTTPS sites with this same code. So, I don't think that this is an encryption problem. There appears to be something weird with the particular site below. The URL is correct and works in Chrome and Edge.

    This particular site got hit with a massive ransomware attack some months back. Something subtle could have changed on this site when putting Humpty Dumpty back together again. My code has been working without problems for the last 5 years. Ideas?

    use strict; use warnings; use WWW::Mechanize; $|=1; #my $page = 'https://contests.arrl.org/publiclogs.php?eid=18&iid=1049' +; my $page = 'https://contests.arrl.org/'; my $mech = WWW::Mechanize->new( autocheck => 1 ); $mech->get($page); exit; __END__ Error GETing https://contests.arrl.org/publiclogs.php?eid=18&iid=1049: Can't connect to contests.arrl.org:443 (Bad file descriptor) at test.p +l line 11. Now with just the minimal URL, I get the same error: Error GETing https://contests.arrl.org/: Can't connect to contests.arr +l.org:443 (Bad file descriptor)
    Update: Changed the code to not verify_hostname. I guess this is then a non-secure connection? I am not sure exactly what this does.
    my $mech = WWW::Mechanize->new( autocheck => 1, ssl_opts => { verify_hostname => 0}, ) +;
FCGI, tied handles and wide characters
2 direct replies — Read more / Contribute
by Maelstrom
on Sep 09, 2024 at 06:48
    I thought my knowledge of unicode handling in perth had evolved to the point where I could include a unicode character in my template files but I thought very wrong. I've been finding the message "Use of wide characters in FCGI::Stream::PRINT is deprecated and will stop working in a future version of FCGI" in my server logs and no amount of setting STDOUT to utf8 encoding through various pragmas or binmode invocations has been able to remove it. Extensive googling turned up the possibility that the FCGI has no concept of Unicode handling and the most thorough explanation I could find was this rant at https://www.apachelounge.com/viewtopic.php?p=37483 which posits that the use of tied handles makes changing STDOUT ineffective and the only solution was to roll your own print routine like..
    sub my_print($) { my($string) = @_; my $is_utf8 = is_utf8(${$string}); _utf8_off(${$string}) if($is_utf8); print ${$string}; _utf8_on(${$string}) if($is_utf8); }
    I could already hear the lynch mobs baying about the scandalous use of _utf8_off and while at this point worrying about making unicode handling even more broken seemed like an academic distinction even I was troubled about turning off the utf8 flag on a string that I knew actually was utf8 but luckily I only had to get halfway through that doomed solution as it turns out my template module will take a file handle to use instead of STDOUT and I could print to the string to get it flagged as UTF like so...
    my $string; open(my $out, "+<", \$string); binmode $out, ':encoding(UTF-8)'; $page->output($out); close($out); print $string;
    Without the binmode on the strings file handle I was getting the generic wide characters warnings from the perl interpreter and nothing from FCGI but with it everything is now working. I came here to ask WTF is going on but in the course of writing out the question I think I actually figured it out but I'm going to post anyway in case it helps the next person trying to find an answer on google. In fact I'm now thinking that use v5.14; in my template module instead of just the main script would also have solved this problem although it feels counter-intuitive that unicode handling in my module isn't inherited from the main script. If I have to find a question I guess maybe it's turned into should I just use feature 'unicode_strings' (or use v5.14) in all libraries going forward or does this just cause the same problem for future users calling the modules from a script that doesn't have that? Ideally I would set a configuration switch to turn it on or off but I don't think use pragmas can be set like that.
Passing argument by reference (for a scalar)
4 direct replies — Read more / Contribute
by jmClifford
on Sep 07, 2024 at 10:51

    Hi. wrt the heading, is there anything to be said for passing a scalar like a string with a reference. I expect this should be considered better since it implies no coping process is used. Possibly it is of no concern for small strings (and small numbers)??

    --------------------- code from web tutorial and added to by me ----------------------------------------- #!/usr/bin/perl use warnings; use strict; my @a = (1,3,2,6,8,4,9); my $m = &max(\@a); # passing an array by reference print "The max of @a is $m\n"; # prints max is 9 sub max{ my $aref = $_[0]; my $k = $aref->[0]; for(@$aref){ $k = $_ if($k < $_); } return $k; } my $string = "This is a string"; printWthStrRef(\$string); # passing string by reference sub printWthStrRef { my $aref = $_[0]; print ${$aref}; #prints the string }
    ---------------------------

    Regards JC.....

Portable Perl Install
4 direct replies — Read more / Contribute
by Anonymous Monk
on Sep 06, 2024 at 17:50

    I have a peculiar problem I have not been able to figure out. I've installed the latest version of Perl (5.40) as a portable instance. The installation is on a shared NFS drive, so that a number of servers have access to it as well. It works as expected on the server where it was originally installed, but when try to run it from the other servers sharing the drive, I get a coredump error. I've tried installing and configuring the Perl instance in a variety of ways with no success. The exact wording of the error is "Illegal instruction(coredump)". I have included the config setting " -Duserelocatableinc", but still no luck.

    Do you have any ideas as to what may be causing this issue?

Postgresql output to file
4 direct replies — Read more / Contribute
by mikebailey
on Sep 05, 2024 at 08:00

    I'm trying to output some log entries for 24hour from the run time, and send to file with that timestamp...Here's where I'm at. Am I going in the wrong direction?

    #!/usr/bin/perl -w query = "SELECT * FROM logs_column WHERE logged_in > NOW()::timestamp +- interval '24hour'"; my $driver = "Pg"; my $database = "dbase"; my $dsn = "DBI:$driver:dbname = $database;host = 127.0.0.1;port = 5432 +"; my $userid = "postgres"; my $password = "postgres"; my $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 }) or die $DBI::errstr; print "Opened database successfully\n"; $ref = $dbh->($query); print ("\n", @$ref);
Using Win32::SerialPort in a module
3 direct replies — Read more / Contribute
by jmClifford
on Sep 05, 2024 at 03:35

    Hi. As the title suggests in an using a supplied module Win32::SerialPort in my own module. I have a few minor issues (I think). The next 3 sections give my module's code, my test routine and console output

    ---------------------------------------------------- Serial.pm #! C:\perl\bin\perl.exe use strict; use warnings; package Serial; # The following 2 lines I suspect are the lines that make a package in +to a module # Also, they seem to make it a member of a class Exporter. require Exporter; my @ISA = qw( Exporter ); # This module "is a" Exporter class member #Now declare what we permit to be visible within the module. my @EXPORT = qw( &Serial_Init &Serial_TrxRcv ); use Win32::SerialPort; use Time::HiRes qw(usleep); my $port; # ############ subroutine Serial_Init ################################ +################### sub Serial_Init { my $port_name = 'COM5'; #my $config_file = 'setup.cfg'; # use this to configure from th +e file $port = new Win32::SerialPort( $port_name ) || die "Unable to open: $^E\n"; # $^E EXTENDED +_OS_ERROR #$port = new Win32::SerialPort($port_name, $config_file) || die "U +nable to open: $^E\n"; $port->handshake('none'); # none dtr rts xoff $port->baudrate(38400); # 19200 57600 1200 9600 115200 4800 +600 2400 300 38400 $port->parity('none'); # space none odd even mark #$port->parity_enable(1); # for any parity except "none +" $port->databits(8); # options 7 8 $port->stopbits(1); # options 2 1 $port->buffers(256, 256); $port->read_interval(0); #RI $port->read_const_time(20); #RC $port->write_char_time(1); #WM $port->write_const_time(100); #WC print "Write settings; "; $port->write_settings || undef $port; # A report out to the console my $baud = $port->baudrate; my $parity = $port->parity; my $data = $port->databits; my $stop = $port->stopbits; my $hshake = $port->handshake; print "B = $baud, D = $data, S = $stop, P = $parity, H = $hshake\n +\n"; # use the below to save the current configuration # if ( $port ) { $port->save('setup.cfg') ; print "Serial Port OK +\n" }; # pack: used for assembling binary stuff # my $status = pack('H2' * 6, 'ca', '00', '01', '00', '00', 'fe'); #$port->write("ati\x0D\x0A"); # carriage return and line feed +: no different #$port->write("ate0"."\r"); #print "test 01\n"; #usleep 0; #print "test 02\n"; } # ############## subroutine Serial_TrxRcv ############################ +################### sub Serial_TrxRcv { my ($cmd) = @_; my $response = ""; #print "cmd; $cmd\n"; $port->write($cmd."\r"); my $loop = 1; while( $loop ) { usleep(200000); # 0.2 of a second my $partial_resp; $partial_resp = $port->input; chomp $partial_resp; $response = $response.$partial_resp; # print $response; #my $responseHex = unpack ('H*', $response); #print $responseHex."\n"; my $last = substr ( $response, -1 ); # get the last charact +er if ($last eq ">") { $loop = 0; $response = substr( $response, 0, -1); + # -1 removes the ">"; chomp $response; next; } print "."; } return $response; } 1; ---------------------------------------------------------------
    --------------------------------------------------------------- # #################################################################### +#### test_Serialpm.pl #!usr/bin/perl use strict; use warnings; use lib '.'; # The Serial.pm is in the current folder use Serial; # use a "1 off type of macro expansion" of the Seria +l module Serial::Serial_Init(); # Initialise the interface my $response = Serial::Serial_TrxRcv("at dp"); # Transmit "AT Diplay + Protocol" and get a response print "Response is; $response\n"; print "Response num char; ".length($response)."\n"; ------------------------------------------------------------------
    ------------------------------------------------------------------ Console output for a simple test; Write settings; B = 38400, D = 8, S = 1, P = none, H = none Response is; AUTO, SAE J1850 PWM Response num char; 21 (in cleanup) Can't call method "Call" on an undefined value at C:/ +Strawberry/perl/vendor/lib/Win32API/CommPort.pm line 193 during globa +l destruction. ----------------------------------------------------------

    My first question is wrt the (in cleanup) warning experienced at the end of the execution. Can I get rid of this?

    In test_Serialpm.pl I have "use lib '.';" to denote where the library is ? Is there a better way ?

    Also, in the same test routine, I have to use long identifiers to access the embedded subroutines. I expected that this was un-necessary ?

    I am using Perl 5.32 on a Win10 64 bit system.

    Regards JC......

[OT] Astronomical puzzling about daylight hours at different latitudes
5 direct replies — Read more / Contribute
by Discipulus
on Sep 04, 2024 at 07:15
    Hello nuns, monks and all astrophiles here around!

    We were sitting looking the sunset at beer o'clock, the fat old Sun submerging into the Tyerrenian Sea.. yeah! not that bad :)

    Then she noticed how fast the daylight hours were shortening at our current 41.45°N latitude but also said that at higher latitudes, for example at 53.07°N the shortening is faster being the sunset ~2.5minutes earlier every day while in the South at 41.45°N is ~1.5minutes earlier in August (the difference for dawns is shorter but still aprreciable... why it is shorter?).

    Then she infered (why dont you have to desume in English?) that, given the faster shortening in the North than in the South, there must be one day (..well probably two) when they meet and because of this it should be one day with the same amount of daylights hours at 41.45°N and 53.07°N not at the same time but in the same day of the year an equal daylight duration.

    By other hand I was arguing that this is impossible and only points at the same latitude can have the same daylight hours in the same day of the year. More: the above reasoning should also be true for very distant points like Tropico and Polar Crown (at least) and this seems to me unreasonalbe.

    If she is right then given the distance between two latitudes should be possible to calculate this phantomatic day of the year at least its distance in days from Solstice.. mumble mumble..

    [Q] who is right? And how to explain the reason in a clean, layman way?

    L*

    There are no rules, there are no thumbs..
    Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.
version error
1 direct reply — Read more / Contribute
by soso_ynak
on Sep 04, 2024 at 06:49

    Hello Monks,

    I'm trying to run a perl script on localhost using Hiawatha server on Linux Puppy (ubuntu based).

    However, I'm getting the following error.

    (The same script can be executed without any problems on the rental server and xampp on Windows.)

    Contents of error.log:

    127.0.0.1|Wed dd Sep 2024 hh:mm:ss +0900|/root/Web-Server/....../targe +t.cgi|Can't locate version.pm in @INC (you may need to install the ve +rsion module) (@INC contains: /etc/perl /usr/local/lib/x86_64-linux-g +nu/perl/5.30.0 /usr/local/share/perl/5.30.0 /usr/lib/x86_64-linux-gnu +/perl5/5.30 /usr/share/perl5 /usr/lib/x86_64-linux-gnu/perl/5.30 /usr +/share/perl/5.30 /usr/local/lib/site_perl /usr/lib/x86_64-linux-gnu/p +erl-base) at /usr/lib/x86_64-linux-gnu/perl5/5.30/Storable.pm line 3.|BEGIN failed- +-compilation aborted at /usr/lib/x86_64-linux-gnu/perl5/5.30/Storable +.pm line 3.|Compilation failed in require at /usr/lib/x86_64-linux-gnu/perl5/5.30/Encode.pm line 56.|BEGIN failed-- +compilation aborted at /usr/lib/x86_64-linux-gnu/perl5/5.30/Encode.pm + line 56.|Compilation failed in require at /root/Web-Server/....../memory.cgi line 6.|BEGIN failed--compil ation +aborted at /root/Web-Server/....../target.cgi line 6. 127.0.0.1|Wed dd Sep 2024 hh:mm:ss +0900|no output

    Note: that if I run

    root# find `perl -e 'print "@INC"'` -name '*.pm' -print

    it will return

    /usr/lib/x86_64-linux-gnu/perl5/5.30/Version.pm

    so I think version.pm is already installed.

    Additional information:

    The 6th line of target.cgi is

    use Encode;

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
    Domain Nodelet?
    Chatterbox?
    and the web crawler heard nothing...

    How do I use this?Last hourOther CB clients
    Other Users?
    Others chilling in the Monastery: (3)
    As of 2024-09-14 07:23 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?
      The PerlMonks site front end has:





      Results (21 votes). Check out past polls.

      Notices?
      erzuuli‥ 🛈The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.