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
CGI Header Breaks on Second AJAX Call
4 direct replies — Read more / Contribute
by brandon8696
on Apr 10, 2025 at 10:28

    Hey Monks,

    My current company has their entire web application written in Perl using the now defunct CGI modules. I have been tasked with making a 2 factor authentication system for it, and this defunct CGI module is the bane of my existence. I am doing a simple AJAX call passing JSON data back and forth. The first AJAX call is fine, but the second AJAX call breaks the CGI header data and spits out my raw file path to my Perl login function.

    I have been running debugging, and the header type is set properly to application/json, yet it is not getting interpreted properly. If I recall, a Stack Overflow post similar to mine seemed to indicate it is a core CGI header caching issue, but I'm genuinely stumped as to what that means conceptually, and what the working solution is. I feel like I can't be the only Perl user stuck using defunct modules trying to use AJAX functionality.

    My temporary working solution has just been to call a CGI redirect instead of returning the second AJAX response, but this was a horrific band-aid I don't want to keep.

    I suppose my questions are, 1) Conceptually what the heck is going on. 2) How can I manually command this CGI module to not short-circuit and respond with what I actually want?

Can't locate loadable object for module DBD::Oracle in @INC
2 direct replies — Read more / Contribute
by Calab
on Apr 09, 2025 at 10:03

    I'm running RHEL9 with perl 5.32. I am trying to get httpd (v2.4.62) to serve some perl scripts through a web browser. When a script is executed that uses Oracle, I get the following error appearing in the httpd/ssl_error_log:

    Can't locate loadable object for module DBD::Oracle in @INC (@INC cont +ains: /usr/local/lib64/perl5/5.32 /usr/local/share/perl5/5.32 /usr/li +b64/perl5/vendor_perl /usr/share/perl5/vendor_perl /usr/lib64/perl5 / +usr/share/perl5)

    The Oracle instantclient v11.2 is installed (I need this version for the DB I connect to) and appears to be working properly. sqlplus runs without issues from the CLI. I've also installed the DBI v1.643 perl module from source. If I install DBI through CPAN it installs v1.647, which causes mismatch issues. When I installed DBI the make test passed, so I assume that it installed properly. make install also seemed to work fine.

    When it says that it can't locate a loadable object for DBD::Oracle, I'm not sure what it's looking for, so I'm having issues verifying that everything did install as expected.

    One thing to note... If I execute the perl script from the CLI as a user, I see the same error. If I execute it as root, it appears to work fine. All the files that I can find appear to have the correct permissions so I don't understand why this is happening.

    Can anyone suggest why this is happening and what I should do to resolve this problem?

    Thanks!

    Update... This doesn't appear to have anything to do with httpd. If I execute the following I can see that root works, but other users do not:

    As root there is no error:
    perl -e 'use DBD::Oracle'

    As a user there is an error:
    perl -e 'use DBD::Oracle' Can't locate loadable object for module DBD::Oracle in @INC (@INC cont +ains: /usr/local/lib64/perl5/5.32 /usr/local/share/perl5/5.32 /usr/li +b64/perl5/vendor_perl /usr/share/perl5/vendor_perl /usr/lib64/perl5 / +usr/share/perl5) at -e line 1. Compilation failed in require at -e line 1. BEGIN failed--compilation aborted at -e line 1.
ItemStyle not returning a unique hash
2 direct replies — Read more / Contribute
by andy4321
on Apr 08, 2025 at 04:33

    I've noticed that I'm getting inconsistent colours (colors).

    I've tracked this down to ItemStyle returning inconsistent hashes (in reality, references to hashes).

    Inconsistent in that:

    • Sometimes, the address of the hash returned are all unique
    • Sometimes, the same address (for a hash) is returned for different ItemStyles
    • The number of duplicated hashes can be very variable

    The code below amply demonstrates the problem:

    #!/usr/bin/perl use Tk; use Tk::ItemStyle; $mw = Tk::MainWindow->new(); $TkStyle{Black } = $mw -> ItemStyle("text", -stylename=>"Black", + -foreground=>"Black", -background=>"Wheat", -selectforegrou +nd=>"LightSeaGreen"); $TkStyle{LightGrey } = $mw -> ItemStyle("text", -stylename=>"LightGrey +", -foreground=>"grey60", -background=>"Wheat", -selectforegrou +nd=>"LightSeaGreen"); $TkStyle{Red } = $mw -> ItemStyle("text", -stylename=>"Red", + -foreground=>"Red", -background=>"Wheat", -selectforegrou +nd=>"LightSeaGreen"); $TkStyle{Blue } = $mw -> ItemStyle("text", -stylename=>"Blue", + -foreground=>"Blue", -background=>"Wheat", -selectforegrou +nd=>"LightSeaGreen"); $TkStyle{RoyalBlue1} = $mw -> ItemStyle("text", -stylename=>"RoyalBlue +1", -foreground=>"RoyalBlue1", -background=>"Wheat", -selectforegrou +nd=>"LightSeaGreen"); $TkStyle{RoyalBlue3} = $mw -> ItemStyle("text", -stylename=>"RoyalBlue +3", -foreground=>"RoyalBlue3", -background=>"Wheat", -selectforegrou +nd=>"LightSeaGreen"); $TkStyle{Green } = $mw -> ItemStyle("text", -stylename=>"Green", + -foreground=>"ForestGreen", -background=>"Wheat", -selectforegrou +nd=>"LightSeaGreen"); $TkStyle{Orange } = $mw -> ItemStyle("text", -stylename=>"Orange", + -foreground=>"Orange", -background=>"Wheat", -selectforegrou +nd=>"LightSeaGreen"); foreach $colour (keys %TkStyle) { $style = $TkStyle{$colour}; $count{$style}++; } foreach $colour (keys %TkStyle ) { $style = $TkStyle{$colour}; printf("%10s has count %d (style=$style)\n", $colour, $count{$sty +le}); }
    There's no MainLoop ... just so that the program exits immediately.

    A typical output may be:

    RoyalBlue3 has count 3 (style=Tk::ItemStyle=HASH(0x556aa72eb408))

    Orange has count 1 (style=Tk::ItemStyle=HASH(0x556aa72eb4b0))

    RoyalBlue1 has count 1 (style=Tk::ItemStyle=HASH(0x556aa72e61d0))

    Red has count 3 (style=Tk::ItemStyle=HASH(0x556aa72eb408))

    Blue has count 3 (style=Tk::ItemStyle=HASH(0x556aa72eb408))

    Green has count 2 (style=Tk::ItemStyle=HASH(0x556aa72e6128))

    LightGrey has count 1 (style=Tk::ItemStyle=HASH(0x556aa72e6188))

    Black has count 2 (style=Tk::ItemStyle=HASH(0x556aa72e6128))

    This does seem very curious and ... wrong?

    Running the script can return very different failure signatures.

    Occasionally, all the references to hashes are unique ... but that seems to be more the exception than the norm.

    I have added a loop (not shown) to the creation of the ItemStyle's ... so that duplicated hashes are deleted and new ones created.

    Sometimes, I have to iterate 3 or even 4 times until I get a completely unique set of hashes.

    Any thoughts?

    Andrew
Undefined import name priority issue?
1 direct reply — Read more / Contribute
by sectokia
on Apr 07, 2025 at 21:39
    Hi Monks, Given 'mylib/json.pm':
    package mylib::json; use Exporter 'import'; our @EXPORT=qw(jsonEncode); use JSON::XS; sub jsonEncode($) { my ($o) = @_; my $j = undef; eval { $j = JSON::XS->new->encode($o); }; return $@ ? undef : $j; }
    And 'mylib.pm':
    package mylib; use Exporter 'import'; use lib 'mylib'; use mylib::json; our @EXPORT = ( @mylib::json::EXPORT );
    Then the following 'test.pl' works fine:
    use strict; use warnings; use lib '.'; use mylib; print jsonEncode({foo => 'bar'});
    However once I add 'use JSON::WebToken' module I get an issue:
    use strict; use warnings; use lib '.'; use mylib; use JSON::WebToken; print jsonEncode({foo => 'bar'});

    This warns:

    Attempt to call undefined import method with arguments ("encode_json" +...) via package "JSON" (Perhaps you forgot to load the package?) at +C:/Strawberry/perl/site/lib/JSON/WebToken.pm line 12.

    I don't understand what I am doing with mylib that impacts what JSON::WebToken does? Without mylib JSON::WebToken is working fine.

Failed match not stored
2 direct replies — Read more / Contribute
by BillKSmith
on Apr 07, 2025 at 16:09
    The match operator returns an (unspecified)false value when the match fails. Why is that value not stored in this case?
    use strict; use warnings; use version '5.38'; use feature 'say'; use Test::More tests=>1; my @arry1 = ('string'=~ m/str/, 'second'); my @arry2 = ('string'=~ m/foo/, 'second'); # no value stored for failed match. is $arry2[1], $arry1[1];

    RESULT

    not ok 1 # Failed test at tryit2.pl line 10 # got: undef # expected: 'second' # Looks like you failed 1 test of 1.
    Bill
(OT) Tracking Issues, Requirements, Tests
5 direct replies — Read more / Contribute
by afoken
on Apr 07, 2025 at 04:41

    Hi!

    I'm searching for a sane tracking software, for developing medical devices. Let me explain:

    At work, we are currently using a really old version of Jira, with add-ons for tracking requirements and product tests. It's so f*ed up that all attempts to update it fail. Updating was never easy, but the last available installer/updater package actively destroys configuration and database, rendering the installation unusable. The fine print: You need to be at the latest version to be able to migrate to the cloud Jira. We can't get to that version. Tech support is not helpful.

    Now, we running one project in a cloud Jira setup, paid for by our customer. I always thought the user interface of the old server installation was bad, but the cloud user interface is a mine field. Ideally, you run it on a separate computer, with mouse and keyboard disconnected. Only connect them if you really want to interact with it. Because almost any key and any click anywhere on the user interface triggers some action, even in empty spaces. The screen is littered with junk that you don't need, stuff that you need is well hidden. And as if all of that was not worse enough, we completely give up control of the data we enter into the system. Atlassian as a long history of mishandling or deleting user data, and we legally have to keep that data. I don't see any sane way of doing that.

    So, guess what? I want to get rid of Jira. I don't want to even have to think about migrating existing data from our existing Jira instances to cloud Jira, and I don't want to use cloud Jira. And as much as I would like to, I don't want to write my own system. I want an existing software, running on a local webserver. I would prefer open source software, so we could tweak things if we really need to. I don't think we need much tech support, so a "community support for free, pay for professional support" model (as for Proxmox or Virtualbox) would be ok. We could pay a license fee, but we are a small company. We mostly do small projects, so license fees that costs in the order of an entire project are simply impossible.

    What do we need?

    • local installation (no cloud)
    • web-based
    • runs on Linux
    • preferably open source
    • issue tracking
    • requirement tracking
    • tracking test plans and test plan execution (product validation, testing that you fulfilled all requirements)
    • a way to import old (non-cloud) tickets from Jira, including how they are linked - a REST API might be sufficient, so I can scrape data from the existing Jira instances

    The classic Bugzilla ticks almost all checkboxes, except that it can't do requirement tracking and test tracking. And it's name is burned because an unloved and unmaintained installation lingered around since well before I was hired. That's clearly not the fault of Bugzilla, but some people are just strange.

    Before Jira, we (the software developers) starting using Redmine just for tracking issues, with the intention to make the entire company using it. Jira won because Redmine wasn't even invited to the race. Redmine has no requirement and test tracking, but at least it has interfaces to third party tools.

    A final note: Jira (with pluins) integrates the bugtracker on the one hand and requirement / tests tracking on the other hand into a single software. We are used to it, but we don't need that integration. Some bug tickets may refer to requirements or tests, but that's all. There is no tracking, not even counting. Nobody checks how many bugs a requirement "attracted". It is convienient to just type FOO-123 and it will be converted to a link to a requirement, just like typing FOO-456 will be converted to a link to an issue. But honestly, copying https://reqs.example.com/req-tracker/req/FOO-123 from the browser's address line into a issue ticket would hurt nobody.

    So, how do you track issues, requirements, tests? Do you know a software that might fit our needs?

    Alexander

    --
    Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)
Why won't my Dancer2 app render any output???
2 direct replies — Read more / Contribute
by traveler
on Apr 05, 2025 at 15:19
    I have been away from the monastery for a while, but I have a very perplexing issue. I am migrating a Dancer2 site from Apache 2.2 to Apache 2.4 (Apache2 under Ubuntu). It works under 2.2 on CentOS, but not on the Ubuntu with 2.4. I copied the whole Dancer2 directory to the new server. I do the output with template commands, if that matters. I read the Apache2 error log and put perl debugs before and after the template command. There are no errors between the debugs. Here is the meaningful part of the Apache conf file. I have verified that apache reads it.
    DocumentRoot /var/webapps/sandbox/public <FilesMatch "\.(?:cgi|shtml|phtml|php)$"> SSLOptions +StdEnvVars </FilesMatch> <Directory "/var/webapps/sandbox/public"> Options +Indexes +FollowSymLinks +MultiViews +ExecCGI AddHandler cgi-script .cgi AllowOverride None Require all granted SSLOptions +StdEnvVars </Directory> RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ /dispatch.cgi$1 [QSA,L] # ScriptAlias / /var/webapps/sandbox/public/dispatch.cgi/ <Location /> # Set up your Dancer2 application SetHandler cgi-script AddHandler application/x-httpd-perl .cgi PerlSetEnv Dancer2_APP /var/webapps/sandbox/bin/app.pl PerlSetEnv DANCER2_CONFDIR /var/webapps/sandbox PerlSetEnv DANCER_CONFDIR /var/webapps/sandbox PerlSetEnv DANCER2_ENV development </Location>
    Here is my Dancer2 config.yml
    # Your application's name appname: "sandbox" # We want to keep session data around so engines: session: YAML: session_dir: /tmp/dancer-sessionstore engines: template: template_toolkit: start_tag: '<%' end_tag: '%>' template: "template_toolkit" session: YAML # The default layout to use for your application (located in # views/layouts/main.tt) layout: "main" # when the charset is set to UTF-8 Dancer2 will handle for you # all the magic of encoding and decoding. You should not care # about unicode within your app when this setting is set (recommended) +. charset: "UTF-8" # template engine # simple: default and very basic template engine # template_toolkit: TT # template: "simple" plugins: Database: driver: 'mysql' database: 'vlabs' host:'something' port: 3306 username: 'rouser' password: 'xxxxxxxxxx' connection_check_threshold: 10
    Here is a code snippet:
    debug "displaying login page"; template 'login.tt', { path => param('requested_path') }; debug "showed login page";
    And the log snippet:
    [sandbox:12160] debug @2025-04-05 15:07:00> displaying login page in / +var/webapps/sandbox/public/../lib/sandbox.pm l. 45 [sandbox:12160] debug @2025-04-05 15:07:00> showed login page in /var/ +webapps/sandbox/public/../lib/sandbox.pm l. 47
    There is a main.tt and a login.tt in the correct places. I get no output in my browser. The page is empty even when I look at the page source. (I do see the favicon.ico.) I am stumped, monks. Any ideas? TIA
Perl JDBC Trino
No replies — Read more | Post response
by mallett76
on Apr 04, 2025 at 16:45

    Not really a question. Well, I did ask this question around 3 or so years ago, and I was finally able to figure it out - how to connect to perl with JDBC. One challenge I found was that the documenetation for modern databases was very sparse. I'm including directions here- in case any one runs into this problem.

    Perl + JDBC + Trino End-to-End Example 1. Prerequisites Strawberry Perl with DBI and DBD::JDBC modules installed. Java Proxy JAR (from DBD::JDBC) running: java -jar jdbc_bridge.jar -port 12345 Trino JDBC Driver (trino-jdbc-*.jar) in your CLASSPATH. 2. Certificate Setup (Optional SSL) If your Trino instance requires a trusted connection: Convert your .crt file to .jks (Java KeyStore): keytool -import -trustcacerts -alias trino -file your_cert.crt -keystore truststore.jks -storepass changeit Then use the truststore.jks with your Java command if needed: java -Djavax.net.ssl.trustStore=truststore.jks -Djavax.net.ssl.trustStorePassword=changeit -jar jdbc_bridge.jar -port 12345 3. Perl Script: trino_connect.pl

    use strict; use warnings; use DBI; # -- Your credentials my $user = "svc-ndevfcollect"; my $password = "yourPasswordHere!"; # Use secure storage in productio +n # -- JDBC URL to Trino (443 confirmed) my $url = "jdbc:trino://query.comcast.com:443?SSL=true&catalog=dx"; # -- JDBC bridge connection (localhost to Java proxy) my $dsn = "dbi:JDBC:hostname=localhost;port=12345;url=$url"; # -- Optional: Print connection hash for debugging my %conn_attrs = ( RaiseError => 1, jdbc_user => $user, jdbc_password => $password, jdbc_catalog => "dx", # Change as needed ); use Data::Dumper; print Dumper(\%conn_attrs); # -- Connect to Trino my $dbh = DBI->connect($dsn, undef, undef, \%conn_attrs) or die "Failed to connect: $DBI::errstr"; print "Connected successfully!\n"; # -- Run sample query my $sth = $dbh->prepare("SELECT current_user"); $sth->execute(); while (my @row = $sth->fetchrow_array) { print "User: $row[0]\n"; } $sth->finish(); $dbh->disconnect();
    4. Launch Instructions Run your Java proxy: java -jar jdbc_bridge.jar -port 12345 Run the Perl script: perl trino_connect.pl 5. Common Issues Error Fix Authentication failed: Unauthorized Confirm user/pass, and that Trino allows password auth. unexpected end of stream Port/firewall/VPN issues. Verify port 443 is reachable. Connection argument is not a valid property Use hashref for properties, not in DSN string. SSL=true not working Confirm the Java bridge trusts Trino’s cert. Use truststore.jks if needed.

Checking string emptiness
3 direct replies — Read more / Contribute
by dave93
on Apr 04, 2025 at 16:43

    In my code I frequently have to write conditions like this:

    if (defined $string and $string ne "") { ..... }

    What I really want is to check if the string is not entirely empty. I would like to be able to do something like if ($string) but this would exclude "0".

    So I hope that there is a shorter and nicer way to do this. For now I have been using a utility strempty subroutine which runs that check but I doubt it's idiomatic.

    In my own code I try to have it so that empty strings are simply undef, where applicable, but sometimes it can't be helped and external modules don't follow this rule hence why I have to write these conditions.

How to test if a string is unicode string?
3 direct replies — Read more / Contribute
by harangzsolt33
on Apr 04, 2025 at 00:49
    What's the best way to tell if a string is unicode or plain ASCII, or do I just use a regex like this?:
    if ($STRING =~ m/[^\x00-\xFF]{1}/) { ... }

    OR MAYBE:

    if (length($STRING) > ($STRING =~ tr|\x00-\xFF|\x00-\xFF|)) { ... }

    I can't think of anything better. Maybe this, but I bet it's slow:

    sub isUnicode { my $L = defined $_[0] ? length($_[0]) : 0; for (my $i = 0; $i < $L; $i++) { ord(substr($_[0], $i, 1)) < 256 or return 1; } return 0; }

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, details, 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, summary, 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.