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
Mojolicious url rewriting
4 direct replies — Read more / Contribute
by rajaman
on Apr 19, 2021 at 19:59

    Hello Monks,

    How can I do the following in the pseudocode below:

    1. the URL '/user/1' should dynamically point and rewrite to '/user/John-H' in the browser address bar and in link mouseover on the page. I have mapped id to value in the 'users' cache.
    2. the URL (with a trailing slash) '/user/1/' should dynamically point and rewrite to '/user/John-H'
    3. restrict the value of id to be an even number and less than 10.

    Thank you!

    #!/usr/bin/env perl use Mojolicious::Lite my $users = Mojo::Cache->new(max_keys => 50); $users->set(1 => 'John H'); $users->set(2 => 'Sam A'); #my $user = $users->get('1'); get '/user/:id' => [id => qr/\d+/] => sub ($c) { $c->render(text => $users{$id}); }; app->start;
extracting only those keys with uniq values in array list
8 direct replies — Read more / Contribute
by v15
on Apr 19, 2021 at 19:08
    Hello everyone I am dealing with Hash of Arrays in Perl. Here is my code so far:
    while(<>){ chomp; my @s = split /\t/,$_; my $r_name = $s[0]; my $seq = $s[9]; push @{$read2seq{$r_name}}, substr($seq,0,12); }
    For every key($r_name) , I have 2 values. I want to print the names of those keys($r_name) where the 2 values for a particular key($r_name) are same. If the 2 values for the particular key are different from each other, then I do not want to output that key. I cannot use the module use List::MoreUtils qw(uniq) since it is not installed on my cluster. How can I do this?
CGI HTML Form Data
6 direct replies — Read more / Contribute
by johnfl68
on Apr 19, 2021 at 17:08

    Hello, I have a form that I need to pre-populate with the previous responses made from that form. I was going to pre-populate the HTML Form with JSON data using jquery and then pass to a CGI to save the results to a JSON file, but Chrome is now blocking external files like this, even though everything is on the same local server.

    So now I am doing this with CGI to load the JSON values and output the HTML with the form data pre-populated.

    So can I submit the form data to the same CGI Perl script? Or do I need to have one CGI for the HTML Form, and another CGI to process the form and save to the JSON file?

    I see lots of examples of posting form data from HTML to a CGI to process, and I have done this before. I am not finding any examples of how to bring the data into the same CGI script from the outputted HTML.

    I am probably missing something simple, but if the only way to do it is with 2 CGI scripts, that will work as well.

    Thank you.

    Original content restored above by GrandFather

    PerlMonks admins, please remove. Unfortunately people here think every question is stupid, and no longer wish to help other people like they used to do. They only want to downvote questions from people trying to learn and ask for help when something is confusing, instead of trying to help them.

    I will look for help elsewhere.

    Thank you.

How do I get a list in a perl hash generated from an XML?
3 direct replies — Read more / Contribute
by PV66
on Apr 19, 2021 at 04:48
    Hi Community, Really hoping to get some perl-wisdom on this one, its my second day working on Perl today, and I'm just stuck with an issue that I can't seem to figure out.

    Basically I have an XML

    <root> <ref name="abc_sia_%version1.ref%"> <func envname = "test01" objectdir = "/home/pv66" base="default_771"/> </ref> </root>
    I want to get the ref name's value, that is "abc_sia_%version1.ref%" as my hash key and the corresponding elements of the tag in a list. So I used Simple XML's function
    my $xml = new XML::Simple; my $data = $xml->XMLin("/home/pv66", ForceArray => 1, KeyAttr => { ref + => "name"}); print Dumper ($data);
    But this gives me
    $VAR1 = { 'ref' => { 'abc_sia_%version1.ref' => { 'func' => [ { 'envname' => 'test01', 'objectdir' => '/home/pv66', 'base' => 'default_771' } ] } };
    And this extra level of hierarchy (after ref) is undesired. I've read at some places that XML::Simple is not the preferred module, and XMLLib should be used, but I couldn't find any resources that drew a parallel to the ForceArray attribute of the XML in method. The desired hash should be:
    $VAR1 = { 'abc_sia_%version1.ref' => { 'func' => [ { 'envname' => 'test01', 'objectdir' => '/home/pv66', 'base' => 'default_771' } ] } };
    Any help pertaining to this would be appreciated.
Why does $Config{ccflags} include "-fwrapv" on many gcc builds of perl ?
1 direct reply — Read more / Contribute
by syphilis
on Apr 19, 2021 at 00:58
    Hi,

    The -fwrapv documentation states:
    This option instructs the compiler to assume that signed arithmetic ov +erflow of addition, subtraction and multiplication wraps around using + twos-complement representation.
    I thought that this was the usual (default) behaviour, anyway. And some quick experimentation I've done supports that notion.
    So, why is the flag specified on so many gcc bulds of perl (eg Windows and Ubuntu) ?

    Is it just a case of deciding that the perl flags might as well be open and specific about this ?
    Perhaps -fwrapv is present simply to alert us to the fact that another option (-ftrapv) is available ? (Not that I think you'd want to build perl with -ftrapv)
    Or are there actually cases where -fwrapv is not the gcc default ?

    Cheers,
    Rob

    PS: For those curious, the -ftrapv documentation states:
    This option generates traps for signed overflow on addition, subtracti +on, multiplication operations.
    The documentation also points out that -ftrapv and -fwrapv override each other - ie, you can have one or the other, but not both.
Injecting a value into HTTP::Header
1 direct reply — Read more / Contribute
by Bod
on Apr 18, 2021 at 16:52

    As part of connecting to LinkedIn using LWP::Authen::OAuth2, I have decided to write a sub-class of LWP::Authen::OAuth2::ServiceProvider which is designed to be sub-classed for exactly this kind of application. This way, it will hopefully be useful to other people.

    However, I need to override a method which has not been designed to be overridden! The LinkedIn API doesn't comply with the OAuth2 spec. The token_type parameter is mandatory but missing. Therefore, I am trying to inject it into the response from LinkedIn by sub-classing the method, adding the missing parameter and then calling the method in the super class. But I am not managing to get the injection to work.

    Here is the sub in LWP::Authen::OAuth2::ServiceProvider that I am overridding:

    The author has commented the point it fails as # Someone failed to follow the spec...!

    This is my sub that overrides the above...

    sub construct_tokens { my ($self, $oauth2, $response) = @_; my $content = eval {$response->decoded_content}; eval {decode_json($content)}; $response->push_header( 'token_type', 'Bearer' ) unless $@; $self->SUPER::construct_tokens($oauth2, $response); }
    I'm trying to set token_type as Bearer so that the rest of the sub in the superclass doesn't complain.

    Is there a good way to to inject this parameter or am I approaching this in the wrong way?

dynamic method creation, dispatch table or pseudo methods?
4 direct replies — Read more / Contribute
by Discipulus
on Apr 18, 2021 at 15:22
    Hello folks,

    I'm planning a little module ( an interactive cli using Term::ReadLine ) but I want make possible for the module user to add some method in the constructor, no Moo* usage is planned so I'd like to see basic perl approaches. At the moment I have soemthing like:

    sub new{ my $class = shift; my %opts = @_; unless ( defined $opts{dumper} ){ require Data::Dumper; # + () to avoid Name "Data::Dumper::Dumper" used only +once: possible typo at # full qualified name to avoid runtime error $opts{dumper} = sub{ print +Data::Dumper::Dumper(\$_[0 +]) } } return bless { %opts }, $class; }

    dynamic method creation

    I can build up a method dynamically with *{"${class}::${meth}"} = sub { my $self = shift; ... } I imagine I can do this directly in the new constructor, right? There are drawbacks or pitfall I overlooked in this approach?

    dispatch table

    The above code for new adds not a method but a property of the object actually being a callable sub: after I can access it like in  $obj->{dumper}->([1,2,{a=>42}])

    I can expand this providing to the module user a method to add commends: use Data::Dump; $obj->add_command( {descr=>'a dumper', command => sub{ dd $_[0] } )

    This seems to me a simpler approach and I cant imagine drawbacks using it. The only one I can imagine is that not being a method I cannot have $self available inside this calls (even if I dont know atm if will be needed).

    pseudo methods?

    But I can craft execute_command to pass $self as first argument:

    sub execute_command{ my $self = shift; my $wanted_command = shift; my @whole_data = @_; $self->{ $wanted_command }->( $self, @whole_data ); }

    This leads to something like a pseudo method; is this too dirty? Has other drawbacks? Do you expulse me from perlmonks if I write it down? :)

    In addition: if new will be as above in the final module, should I add Data::Dumper to prerequisites? I'd say yes but... if not Data::Dumper but Math::Mersenne::Primes was the case? I must add it to prerequisites even if there is the chance it will be never loaded?

    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.
Plack middleware sets Plack env value but it's not consumable in the same builder
2 direct replies — Read more / Contribute
by 1nickt
on Apr 18, 2021 at 09:50

    Learned friends,

    I am attempting to convert my Starman log to structured JSON to match the app logs, and to add a request ID to all the log entries starting with the Starman log.

    I have both of these things working separately but they are not playing nicely with each other. I used Plack::Middleware::AccessLog::Structured for the log, and as advertised I get nice single-line JSON in my access_log. I also used Plack::Middleware::RequestId to generate the request ID, and this too is working, in the sense that in the application code, the value is present in the Plack env.

    However, the initial log entry from Starman cannot read the request ID from the env, and I suspect it's because it's in the same builder block. I have tried pushing the value to an HTTP header and the regular ENV as well as the Plack env, and all attempts have the same outcome: the value is null in the log for the Starman entry and present for the app log entries. Here's my app.psgi:

    use Meta::Portal; use Plack::Builder; use Plack::Middleware::AccessLog::Structured; use Plack::Middleware::RequestId; use Data::GUID; my $app = Meta::Portal->to_app; builder { enable 'RequestId', id_generator => sub { Data::GUID->new->as_string; }; enable 'AccessLog::Structured', callback => sub { my ($env, $message) = @_; #use Data::Dumper; #warn Dumper $env; $message->{date} = Time::Moment->from_epoch( delete $message-> +{epochtime} )->strftime('%F %T%6f'); $message->{tracking_id} //= $env{'psgix.request_id'}; return $message; }; $app; };

    Thanks for any help!


    The way forward always starts with a minimal test.
Disable Plack::Middleware::AccessLog
2 direct replies — Read more / Contribute
by 1nickt
on Apr 17, 2021 at 20:09

    Learned friends,

    The doc for Plack::Middleware::AccessLog states This middleware is enabled by default when you run plackup as a default development environment.

    I am wanting to run another middleware for logging and thus wish to disable the default. Can anyone tell how?

    Thanks!


    The way forward always starts with a minimal test.
grep all matches
3 direct replies — Read more / Contribute
by noviceuser
on Apr 17, 2021 at 14:48

    Below is code snippet where i am reading a log file and grepping the failed testcase, then if the failed testcase is also mentioned in the reference file (/icd/eps2/kaakash_p4/readSyntechScript/failedTest) then need to ignore testcase. But, i want to modify this code for more than 1 testcase, kindly help as i am new to perl

    Note: utils commands are in-house package, please ignore

    my $results = ''; my $cmd = "ls /icd/eps2/kaakash_p4/readSyntechScript/testsuites_re +port* | tail -1"; utils::execCommand(Command => $cmd, Results => \$results); chomp($results); my @reportContents = utils::getFileContents("$results"); my ($failedTest) = grep { /FAIL/ } @reportContents; $failedTest =~ /\|\s+(\w+)/g; my $failedTestsuite= $1; chomp ($failedTestsuite); print "Failed Testsuite = $failedTestsuite\n"; my $ignoreTestFile = "/icd/eps2/kaakash_p4/readSyntechScript/faile +dTest"; my @ignoreContents = utils::getFileContents("$ignoreTestFile"); my $referenceFailedTest = $ignoreContents[0]; chomp($referenceFailedTest); print "Reference Failed Testsuite = $referenceFailedTest\n"; if ("$failedTestsuite" eq "$referenceFailedTest") { print "ignore testcase"; }

    2021-04-18 Retitled by Discipulus, as per Monastery guidelines


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.