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
Knowing when a code string contains code that will be executed at compile-time/end?
No replies — Read more | Post response
by perlancar
on Aug 15, 2020 at 01:11

    Hi monks,

    I am given a code string by user, and wants to know if the code contains statements or special blocks that are executed not in regular run time. For example:

    use Foo "bar"; bar(); # yes bar(); baz() if $qux; # no bar(); END { warn "qux" } # yes

    The reason is because I need to eval the code string and later dump the code back to string. And these statements/blocks do not get included. Demonstration:

    % perl -MData::Dumper -E'$Data::Dumper::Deparse=1; print Dumper(eval q +[sub {use File::chdir; local $CWD="/"; END { warn } }])' $VAR1 = sub { use feature 'current_sub', 'bitwise', 'evalbytes', 'fc', ' +postderef_qq', 'say', 'state', 'switch', 'unicode_strings', 'unicode_ +eval'; local $CWD = '/'; }; Warning: something's wrong at (eval 5) line 1.

    I want to be able to warn the user when her code contains these things. I'm thinking of PPI right now, but that seems too heavy. Ideas on other ways to do this?

chmod fails
3 direct replies — Read more / Contribute
by Umdurman
on Aug 14, 2020 at 16:33
    Dear friends, I have a nasty problem. I am running a webserver on OSX. The images for the webserver are produced on a Windows machine. The Windows machine has a network connection with the OSX Server. Once the images are ready we drag and drop them from the PC into the image directory on the Mac. If I look in the info of the transferred files I see the owner is the same as the server but everyone is "no access". The image files fail to render in the webserver. I figured to make a nice script that chmods the transferred files and copy them in the right directory. Chmodding however does not work at all. I used to do this file preparing from one Mac to the other, the Server without this problem. Anyone with bright idears? Thanks in advance! No special code, just : chmod 755, $file_name or die "Can't chmod $old because: $!\n"; Please see this link to illustrate the problem: https://apple.stackexchange.com/questions/316205/no-write-permissions-after-copy-files-from-windows Ton
Opening a file in Perl
2 direct replies — Read more / Contribute
by aartist
on Aug 14, 2020 at 15:06
    What is Perl equivalent of this python code ?
    with open("welcome.txt") as file: 
    There is a context manager magic to handle failure in python. How to achieve similar thing in Perl ?
FindBin and Tainted
2 direct replies — Read more / Contribute
by mikkoi
on Aug 14, 2020 at 05:36

    I have the following code:

    use strict; use warnings; use FindBin 1.51 qw( $RealBin ); use lib "$RealBin/../lib"; use MyLib;

    when I run it with Perl 5.28.1 as perl -T ./bin/perl-taint.pl I get the following error:

    Insecure dependency in require while running with -T switch at ./bin/p +erl-taint.pl line 7. BEGIN failed--compilation aborted at ./bin/perl-taint.pl line 7.

    FindBin operates in BEGIN section, so how - if possible - can I untaint the path?

How to trim a line from leading and trailing blanks without using regex or non-standard modules
5 direct replies — Read more / Contribute
by likbez
on Aug 13, 2020 at 22:24

    Is there any way to trim both leading and trailing blanks in a text line (one of the most common operations in text processing; often implemented as trim function which BTW was present in Perl 6) without resorting to regular expressions (which are definitely an overkill for this particular purpose)? This is clearly an important special case.

    So far the most common solution is to use something like $line =~ s/^\s+|\s+$//g which clearly is an abuse of regex.

    See, for example, https://perlmaven.com/trim

    Or install String::Util which is a not a standard module and as such creates difficulties in enterprise env.

Why split function treats single quotes literals as regex, instead of a special case?
3 direct replies — Read more / Contribute
by likbez
on Aug 13, 2020 at 22:21

    It looks like Perl split function treats single quotes literal semantically inconsistently with other constructs

    But not always :-). For example

    ($line)=split(' ',$line,1)
    is treated consistently (in AWK way). This is the only way I know to avoid using regex for a very common task of trimming the leading blanks.

    In general, split function should behave differently if the first argument is string and not a regex. But right now single quoted literal is treated as regular expression. For example:

    $line="head xxx tail";
    say split('x+',$line);
    will print
    head  tail

    Am I missing something? BTW this would be similar to Python distinguishing between split and re.split but in a more elegant, Perlish way. And a big help for sysadmins.

B::Hooks::OP::Check::StashChange causes split to disappear
1 direct reply — Read more / Contribute
by kroach
on Aug 13, 2020 at 19:49

    B::Hooks::OP::Check::StashChange allows one to run a callback whenever the current package changes during compilation. If a hook is installed, all subsequent calls to split appear to be removed. How is this possible?

    Here's some code without a hook being installed:
    INSTALL_HOOK=0 perl -MO=Deparse -MB::Hooks::OP::Check::StashChange -e +'BEGIN { my $id = B::Hooks::OP::Check::StashChange::register(sub {}) +if $ENV{INSTALL_HOOK}; } print split "x", "1x2"' use B::Hooks::OP::Check::StashChange; sub BEGIN { my $id = B::Hooks::OP::Check::StashChange::register(sub { } ) if $ENV{'INSTALL_HOOK'}; } print split(/x/, '1x2', 0); -e syntax OK
    and here's the same code with the hook enabled:
    INSTALL_HOOK=1 perl -MO=Deparse -MB::Hooks::OP::Check::StashChange -e +'BEGIN { my $id = B::Hooks::OP::Check::StashChange::register(sub {}) +if $ENV{INSTALL_HOOK}; } print split "x", "1x2"' use B::Hooks::OP::Check::StashChange; sub BEGIN { my $id = B::Hooks::OP::Check::StashChange::register(sub { } ) if $ENV{'INSTALL_HOOK'}; } print 'x', '1x2'; -e syntax OK

    As you can see, "split" disappeared and it's arguments are simply being printed. The module code itself is pretty short but given my lack of experience with XS I can't pinpoint the issue. How can a builtin get disabled like this?

[OT] Filtering / Highlighting serial port input / PuTTY output
3 direct replies — Read more / Contribute
by afoken
on Aug 13, 2020 at 11:24


    I'm working with two systems, both without real(TM) operating systems. One is a microcontroller, running our software on bare metal, the other is my PC running Windows 7. The microcontroller writes debug output to one of its serial ports, which is connected to the PC. On the PC, putty simply displays whatever text is written to the debug port. A common setup at work, but I'm drowning in debug output. All of it is kind-of relevant, but usually only a little bit of the debug output is relevant for the current problem.

    (And no, I can't disable the irrelevant debug output on the microcontroller in reasonable time.)

    On a real operating system, I would run something like this:

    stty raw 115200 < /dev/ttyS0 grep --perl '^(Foo|Bar):' < /dev/ttyS0

    But I'm stuck on Windows. I need some way to print input from a serial port to a fully resizeable window, optionally with a filter that either omits or highlights incoming lines. PuTTY does all I need, except for filtering. Trying to run anything perl in a command window already fails, because the console window has a maximum width of 80 characters, which is little more than a third of the screen width.

    And I don't have the time to hack a special version of PuTTY or a large perl application.

    A Google search for "putty filter" and similar combinations results in lots of ugly teapots, anti-glare filters, and some other wierd stuff, but nothing even close to filtering output from PuTTY.

    Any hints? E.g. how to get that !%&%$*! standard console window to allow free resizing? Or a tool that can do what I want?


    Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)
pass one or more directories into a file and use that as INPUT to a called script
4 direct replies — Read more / Contribute
by noviceuser
on Aug 13, 2020 at 10:46

    i want to write a piece of code say comp.pl where i can pass one or more comma separated directories into a file and use that as INPUT to a called script runTest.pl .

    here, directories contains multiple files having testcases

    below, $runPath -> path for testcases file / directory containing such file

    $runTest -> command line passed testcases file or command line passed directory where such multiple testcases files exist

    my $testFile = ''; if (-f "$runPath/$runTest") { $testFile = "$runPath/$runTest"; } else { open (my $RF, '>', 'testFile'); print {$RF} map { "$_\n" } split(/,/, $runTest); close $RF; $testFile = "$runPath/$testFile"; } $status += utils::execCommand(Command => "$runTest.pl -f $testFile;

    the above $status line is working fine when passing testFile from command line but not working when passing directory/directories.

    example: comp.pl --runTest testDirectory1, testDirectory2

    so when i am executing the comp.pl script, it is not reading the files and its listed testcases under testDirectory1 and testDirectory2. it is just printing testDirectory1 and testDirectory2 line by line inside <testFile>

SSL connect attempt failed
3 direct replies — Read more / Contribute
by Anonymous Monk
on Aug 12, 2020 at 12:49
    Hi Monks!

    Is there a way to pass a new SSH server host keys since it was changed in the host server or to update this key from a Perl scrip using Net::FTPSSL.
    When my Perl script runs it gives this error message:

    "Can't open xxx.xxx.xxx.xxx: SSL connect attempt failed"

    Posting a test code here which gives the same error. If I use Filezilla, it detects that the server key was changed, asks to accept the new key and connects, but from the Perl script, it doesn't, I guess I have to send a flag or the key it sefl in the code, thats where my problem is, any suggestions?

    Test Code:
    #!/usr/bin/perl use strict; use warnings; use Net::FTPSSL; open (STDERR, "> logfile.txt"); # Redirects STDERR to this file. my %connectionHash = ( Port => 21, Encryption => 'E', Debug => 1, OverridePASV => 'xxx.xxx.xxx.xxx', Croak => 0, PreserveTimestamp => 0, ); my %sslHash = ( #SSL_cert_file => '', #SSL_reuse_ctx => '', SSL_key_file => 'MD5:9f:...f9', #SSL_ca_file => '', #SSL_use_cert => 1, ); $connectionHash{SSL_Client_Certificate} = \%sslHash; my $ftps = Net::FTPSSL->new( 'xxx.xxx.xxx.xxx:', %connectionHash, ); $ftps->login ('user', 'pass') or warn "Could not login to xxx.xxx.xxx +.xxx: ", $ftps->message; $ftps->nlst(); $ftps->quit();

    Thanks for looking!

Add your question
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.