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
Reading a hash structure stored in a file
3 direct replies — Read more / Contribute
by sam1990
on Jan 15, 2019 at 15:08

    Hello, I have a file that has a hash stored in it. I am trying to read that hash as it is using eval but I am getting following error: Global symbol "%hash1" requires explicit package name (did you forget to declare "my %hash1"?) at line (print Dumper(\%hash1);) 14. Execution of aborted due to compilation errors. Please help me understand the issue here, thank you : my %hash1 = (hello => 1, hi =>2 ); #!/home/utils/perl5/perlbrew/perls/5.24.2-021/bin/perl use strict; use warnings; use Path::Tiny qw( path ); use Data::Dumper; my $file = ''; open(my $fh, '<', $file) or die "Could not open file $file"; eval($fh); close $fh; print Dumper(\%hash1);
Invoke the Perl string interpolation engine on a string contained in a scalar variable.
1 direct reply — Read more / Contribute
by ibm1620
on Jan 15, 2019 at 12:49
    I want to be able to take arbitrary lines containing variables that are defined in the program, and interpolate them.
    #!/usr/bin/env perl use 5.010; use warnings; use strict; my $var1 = "abel"; my $var2 = "baker"; my $var3 = "charlie"; while (my $line = <DATA>) { chomp $line; say "Before interpolation: $line"; say "After interpolation: " . perform_interpolation($line); say ''; } sub perform_interpolation { my $text = shift; # now what? } __DATA__ I'd like to see this one: $var1. How about \$var3? You shouldn't interpolate \$var3 (but it would be ni +ce if you'd remove the backslash) Try a concatenation: $var1$var2
    I've seen String::Interpolate mentioned in my searches, but unless I'm misunderstanding something, I'd have to know in advance what variables I'd be interpolating

    What I'm trying to do is create a program template where a comment block right after the shebang line (possibly containing scalar variables like $program or other constants or environment variables) can be rendered to produce a usage statement.

    The perform_interpolation() subroutine would be part of the template and wouldn't know specifically what variables the programmer might want to interpolate for the usage statement.

    Can String::Interpolate do this? Or is there a simpler way?

Comparing multiple strings
3 direct replies — Read more / Contribute
by bigup401
on Jan 15, 2019 at 11:26

    How can i Compare multiple strings in faster way

    $name = "john"; $t1 = "john"; $t2 = "john"; if ($name ne $t1 || $t2) { do something }
SIGALRM in perl
1 direct reply — Read more / Contribute
by anjultyagi
on Jan 15, 2019 at 06:24

    Hi Expert, I am using the PERL language with the PostgreSQL database and in a couple of database function, we are using the plperl as language. We are basically calling the SOAP API in the function, however yesterday we faced the issue where PARL had sent the SIGALRM signal and my database got crashed. Can you please review and help me to resolve the issue, either by a code change or a configuration change.

    CREATE OR REPLACE FUNCTION sendclaimcoversheet( text, text) RETURNS integer AS $BODY$ use strict; use warnings; use SOAP::Lite; use Try::Tiny; use Time::Piece; my $first = $_[0]; my $second = $_[1]; try { my $host = `hostname`; my $rv = spi_exec_query("select * from getsprocurl('sendclaimc +oversheet','".$host."')"); my $url = $rv->{rows}[0]->{ret_url}; elog(NOTICE, 'Host Name ' . $host . ' URL '. $url ); my $soap = SOAP::Lite->new(); my $service = $soap->service($url); my $response = $service->sendClaimCoversheet($first, $second +); return $response; } catch { my $ex = $_; return 'SOAPFAULT: ' . localtime->strftime('%m/%d/%Y') . ' ' . + $ex; } $BODY$ LANGUAGE plperlu VOLATILE STRICT COST 100; ALTER FUNCTION sendclaimcoversheet(text, text) OWNER TO postgres;
Win32::GUI and threads issue
2 direct replies — Read more / Contribute
by Garden Dwarf
on Jan 15, 2019 at 05:20

    Hello Monks!

    I am trying to create a Win32 application (with Strawberry Perl (v5.14.4) on Win10) displaying graphic computations. In order to optimize the process, I want to divide the management of my virtual buffer into small pieces computed by individual threads, then compile the results and copy the virtual buffer on the screen.

    My problem is the combination of Win32::GUI and threads (I have also tried forkmanager without success). Threads without Win32 is ok, Win32 without threads is ok, but using both is not. Here is a simple sample code to illustrate the issue (you can enable/disable the use of Win32 with the variable $use_win or change the amount of threads with the variable $t_amount):

    #!/bin/perl use Win32::GUI(); use threads; use strict; use warnings; use Data::Dumper; my $use_win=1; # Create Win32 GUI interface (1) or not (0) my $t_amount=4; # Amount of threads to create my $textbox; my $win; my $draw; if($use_win){ # Initialize window $win=new Win32::GUI::Window( -left => 0, -top => 0, -width => 300, -height => 300, -name => "Window", -text => "Test", ); $win->InvalidateRect(1); $textbox=$win->AddTextfield( -name => "Output", -left => 5, -top => 5, -width => 275, -height => 255, -text => ""); # Start application $draw=$win->AddTimer('draw',1000); $win->Show(); Win32::GUI::Dialog(); }else{ draw_Timer(); } sub Window_Terminate{-1} sub draw_Timer{ my @threads; my @ret; my $c; my $d; # Assign range of computation to fork processes foreach $c(1..$t_amount){ $d=$c-1; push(@threads,threads->new(\&draw,($d*10),($d*10+10))); } foreach my $thread(@threads){ @ret=$thread->join; foreach my $data(@ret){ $use_win?$textbox->Append("|".$data):print"|".$data; } $use_win?$textbox->Append("\n"):print"\n"; } } sub draw{ my $begin=shift; my $end=shift; my @tbl; my $cpt; for($cpt=$begin;$cpt<$end;$cpt++){ push(@tbl,$cpt); } return(@tbl); }

    Any help would be welcome. I have searched for previous posts without finding a solution. I also googled with no luck. Thanks in advance!

Using AUTOLOAD with Moo
4 direct replies — Read more / Contribute
by nysus
on Jan 14, 2019 at 20:04

    I'm pretty sure I've made a bad design decision but not sure what else I can do with Moo. I want a attribute to handle methods if they don't exist:

    package Mac::ApperlScript::App::Finder::Window ; use Moo; use Mac::AppleScript::Glue::Object; use namespace::autoclean; our $AUTOLOAD; has 'obj' => (is => 'ro', required => 1, isa => sub { die 'Improper object passed' unless ref $_[0] eq 'Mac::AppleScript::Glue::Object' }, writer => '_set_obj', ); sub AUTOLOAD { my $s = shift; my @al = split /::/, $AUTOLOAD; my $method = $al[-1]; return $s->obj->$method; }

    So I delegate all methods that don't exist to the obj attribute. The problem is that methods like DESTROY seem to get diverted to the AUTOLOAD subroutine. Is there a better way to achieve what I want to do?

    $PM = "Perl Monk's";
    $MCF = "Most Clueless Friar Abbot Bishop Pontiff Deacon Curate Priest Vicar";
    $nysus = $PM . ' ' . $MCF;
    Click here if you love Perl Monks

Learning to use fork()
3 direct replies — Read more / Contribute
by ovedpo15
on Jan 14, 2019 at 17:46
    I'm trying to make my script more efficient so I decided to learn how to use fork.
    This question is more on how to write it nice and clean
    I have about 13 different calls that create files. Those calls are not depended and they can run parallel:
    create_file('A'); create_file('B'); create_file('C'); create_file('D'); create_file('E'); ...
    I understand how to create a fork and how to check if there is one and why it is important to use the wait function.
    But I don't know how to make it look nice, clean and readable. Should I create a special function which will be called every time I need to create X (for example 5) forks? How should I keep track of those forks? If for example, I have 13 things I can run parallel, should I use 13 forks (running on a strong machine)? Meaning how to determine how many forks to use?
    I would really love to see some real example with for example 13 different calls.
Case where '( shift @_ )[ 0, 0 ]' returns only one value?
5 direct replies — Read more / Contribute
by rsFalse
on Jan 14, 2019 at 15:58
Reorganizing hash
3 direct replies — Read more / Contribute
by ovedpo15
on Jan 14, 2019 at 08:51
    This question I posted on SO (but didn't get any comments) - (link:
    Consider the following hash of files:
    %files_data = { './' => { 'pid' => { '56061' => 1, '56065' => 1 } }, 'file1' => { 'pid' => { '56061' => 2 } }, 'file2' => { 'pid' => { '56065' => 2 } }, './src/bin/perl' => { 'pid' => { '56061' => 1, '56065' => 1 } } };
    Also consider the following hash of process_data:
    %process_data = ( '56061' => { 'parent' => 'NA', 'name' => 'file1' }, '56069' => { 'parent' => '56065', 'name' => 'echo Hello_file1' }, '56062' => { 'parent' => '56061', 'name' => 'echo Hello_file2' }, '56065' => { 'parent' => '56061', 'name' => 'file2' } );
    I would like to iterate through the `$files_data` hash and for each file get the chain of files.
    So I'll get the following hash:
    %hash = ( 'file1' => { '/src/bin/perl' => 1, 'file2' => { '/src/bin/perl' => 1, './' => 1 }, './' => 1, } );
    I need to follow the pid chain up to the main parent ('NA') for each file.
    What would be the most efficient way to solve it? I need some guidance on how to implement it.
    I'll try to explain how my logic works and show some code. lets take for example `'./'` file. It has a pid `56061` so we go to the `%process_data` and see `'file1'` (which is a file). Also we see that the parent of `56061` is `NA` so we stop and get:
    file1 => ./ But `./` has another pid - `56065` so we go to `56065` and see `file2` (which is a file). Then we go to `56061` which has `file1` (which is s file). so we get:
    file1 => file2 => ./
    Combine it:
    file1 => { ./, file2 => ./ }
    I would like to build a process file chain (only with files). the `%files_data` contains valid files and `%process_data` contains the hierarchy of the process we need to follow.
    Some of what I tried to do:
    create_proc_tree(\%process_data,\%files_data); sub create_proc_tree { my ($proc_href,$files_href) = @_; my %hash; while (my ($file, $procs) = each %{$files_href}) { foreach my $pid (keys(%{$procs->{'pid'}})) { my $prev_file = $file; do { my $parent_id = $proc_href->{$pid}{parent}; my $parent_name = $proc_href->{$pid}{name}; if ($prev_file eq $parent_name) { $hash{$parent_name} = 1; } else { $hash{$parent_name} = { (%{ $hash{$prev_file} // { +} }, $prev_file) }; delete($hash{$prev_file}); } $prev_file = $parent_name; my $parent_name = $proc_href->{$parent_id}{name}; } while(defined($parent_name)); } } print Dumper(\%hash); # Printing for debug }
    It does not quite do what I want. The hierarchy is not valid. I'm not sure what is wrong with the algorithm, it feels like true but the output is not as expected.
    I think that its because I counted the data to many times without deleting.
    It made me think that this algorithm is not efficient and messy. I have found out that we can use 'eval' in order to convert string to hash:
    use Data::Dumper; $abc = "Mouse=>Jerry, Cat=>Tom, Dog=>Spike"; my %hash = eval( "( $abc )" ); print Dumper(\%hash);
    Maybe a better approach will be to build a string like and then convert it to hash (although I read a comment saying that it is a bad why to use eval).
    Also, I though of finding first the Main parent file and the go until I get the current file. How should I solve this issue? What would be the best approach?
Dbic and inflating Oracle DATE columns - solved
1 direct reply — Read more / Contribute
by Ea
on Jan 14, 2019 at 05:27
    Newbie trying to get DBIx::Class to work with Oracle DATE columns. Managed to get my error to go away, so I'm putting this out there for expert comment and for those newbies searching on the same problem.

    I used dbicdump with components=["InflateColumn::DateTime"] on an Oracle schema which produced a Result class which has

    __PACKAGE__->load_components("InflateColumn::DateTime"); ... __PACKAGE__->add_columns( "start_time", { data_type => "datetime", is_nullable => 1, original => { data_type => "date" }, }, );
    but after searching with dbic and getting a resultset
    $resultset = $schema->resultset('Ical') ->search({ uid => $id });
    calling $resultset->start_time would give me DBIx::Class::InflateColumn::DateTime::catch {...} (): Error while inflating '24-APR-18' for start_time on Timetable::Schema::Result::Ical: Invalid date format: 24-APR-18. There are lots of hints in the documentation, but nothing explicit on how to avoid this error.

    I found that the error went away when I added the on_connect_call option to the connect method.

    my $schema = Timetable::Schema->connect("dbi:Oracle:$schema_name", $db_username, $db_password, {on_connect_call => 'datetime_setup'} );

    Just thought I'd get it down while it was fresh in my mind and I'll update the post when I know more about what I've done.



    The more documentation I read, the more I think I did the Right Thing.
  • How to connect
  • How to customize InflateColumn (which I didn't need)


    Sometimes I can think of 6 impossible LDAP attributes before breakfast.

    Mojoconf was great!

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.