Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
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
PDL Advent calendar
No replies — Read more | Post response
by etj
on Nov 04, 2024 at 10:08
Signal Apache that Response is Complete
1 direct reply — Read more / Contribute
by rhumbliner
on Nov 02, 2024 at 00:04
    I'm using a Perl script with Apache and mod_perl to generate dynamic responses to client requests. At times I would like to signal Apache that my response is complete so the client can begin processing the response while on the server I perform a bunch of other clean up tasks. My code looks like this
    use CGI::Simple; my $q = new CGI::Simple; print $q->header(%HTTP_HEADERS); print $html; # response complete ... continue with various tasks ...
Inverse slices
5 direct replies — Read more / Contribute
by Anonymous Monk
on Oct 31, 2024 at 20:07
    Is there a better way to get an inverse slice than to do something like:
    my @array = ('aa'..'zz'); my @slice_idx = (6,13,42,66,69); # Slice my @slice = @array[@slice_idx]; my %slice_idx = map { $_ => 1 } @slice_idx; my @invslice_idx = grep { ! exists $slice_idx{$_} } 0 .. $#array; # Inverse slice. my @invslice = @array[@invslice_idx];
Unusual "Can't locate object method"
3 direct replies — Read more / Contribute
by geoffleach
on Oct 31, 2024 at 17:47
    When executed
    use Audio::TagLib; $test = shift; $file = Audio::TagLib::FileRef->new($test); say 'title:', $file->tag()->title()->toCString(); say 'track', $file->tag()->track()->toCString();
    Perl says
    title:Title Test Can't locate object method "toCString" via package "0" (perhaps you fo +rgot to load "0"?) at ./taglib_test.pl line 9.
    Note that the two calls are identical, except for the title/track. Similar calls in a different context don't have the problem.

    My question: How can I discover what Perl sees that results in the error? Many thanks. (FWIW the module reports content from a MP3 file)

pop() on a fast multi-core cpu
4 direct replies — Read more / Contribute
by Anonymous Monk
on Oct 30, 2024 at 15:15

    While I'm waiting for my password ....

    My computer is a new Dell Inspiron with an Intel i9 3900.

    I wrote a cli similation of a simple solitaire card game that I knew the winning stats for.

    I was disappointed in the results; but here is the culprit.

    pops and shifts and individual selections from lists were unstable about 5% of the time.

    Lots of run-time warning msgs about uninitiated values and more failures that went undetected.

    Unitiated cards in the source list, and uninitiated variables supposed to have receive popped or selected cards

    The code sequence causing the problem was : search a nine card list for a pair, cover both cards of a pair with cards from the stock, search the updated list for a pair or pairs.

    One or both of the covering cards never arrived maybe 5% of the time.

    So, the basic question is : with twenty some CPU cores looking for work, is Perl really up for this environment?

    And obviously, any other posts on this?

Closures and scope of lexicals
4 direct replies — Read more / Contribute
by haj
on Oct 30, 2024 at 12:42

    I guess we have all been there: You make an "obviously trivial" change ... and the code fails to behave. This is a stripped down version of the "good" code:

    use 5.030; use warnings; my @subrefs = (); for my $i (1..3) { push @subrefs, sub { print $i; }; } for (@subrefs) { $_->(); }

    This prints 123, as I would expect.

    The "trivial" change:

    use 5.030; use warnings; my @subrefs = (); my $i = 0; for (1..3) { $i++; push @subrefs, sub { print $i; }; } for (@subrefs) { $_->(); }

    This prints 333. WTF?

    It seems the anonymous subroutine is not built with the value of $i, but with a reference to $i. I would not have expected this. Is this a bug, a quirk, or something which can be found documented somewhere?

    Edited to add:

    I wrote that bad code BC (Before Coffee), remembering that I had done something very similar before. I have now dug that up:

    use 5.030; use warnings; my @subrefs; my $i = 0; for (1..3) { push @subrefs, sub { print ++$i }; } for (@subrefs) { $_->(); }

    This prints 123. The difference is that the increment is done when the subroutine is called, not when the subs are declared and pushed to the array. In BC state I failed to see that difference.

DBD::mysql::st fetchrow_hashref failed: fetch() without execute() at
3 direct replies — Read more / Contribute
by Digioso
on Oct 29, 2024 at 08:51
    Hi Monks, I am having some trouble with a MySQL statement, or rather the fetchrow_hashref to get the data. It always returns the error message "DBD::mysql::st fetchrow_hashref failed: fetch() without execute() at", but nevertheless the results are completely fine and as expected. I have no idea what is causing this error.
    $error returns 1

    My code:
    my $dbh = DBI->connect("DBI:mysql:$db:$host", $user, $pw) || die; my $sql; my $sth; if($ENV{'REQUEST_METHOD'} eq 'GET') { my $daten; $daten = $ENV{'QUERY_STRING'}; my @formularfelder = split(/&/, $daten); my @formular = (); my $i=0; foreach my $feld (@formularfelder) { (my $name, my $value) = split(/=/, $feld); $value =~ tr/+/ /; $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg; $value =~ s/<!--(.|\n)*-->//g; $formular[$i] = $cgi->escapeHTML($name); $i++; $formular[$i] = $cgi->escapeHTML($value); $i++; } if(!defined $formular[0] || $formular[0] ne "dl" || ! defined $for +mular[1] || $formular[1] !~ /^\d+$/) { Navi::print_navi(": Nice try... :"); print qq{<div id="category">[ NICE TRY ]</div>}; print "<b>Nice try...</b>"; } else { $sql = qq{select p.category as category, p.titel as titel, p.b +eschreibung as beschreibung , c.werbung as werbung from movie_project +s as p join movie_categories as c on c.id = p.category WHERE p.id = ? +}; $sth = $dbh->prepare($sql) or die "Error: $DBI::errstr"; my $error = $sth->execute($formular[1]) or die "Error: $DBI::e +rrstr"; print "$error\n"; while (my $ergebnis = $sth->fetchrow_hashref()) {
How do I call a sub using a variable as its name, objectively
4 direct replies — Read more / Contribute
by misterperl
on Oct 28, 2024 at 15:10
    $ARGV[0] is my subroutine name, and $ARGV[1] it's arg. The sub is a method in a class and I blessed object $A with new(), that class has a sub with a name contained in $ARGV[0].

    I researched using a variable as a sub name and found may examples with syntax like \$sub , &$sub , \&$sub, "do", "eval", even a seemingly unusual &{\&{$sub}}();

    I can get some of these to work on a local sub, but not as part of my class object $A , trying syntax using those examples, like:

    %$A->$ARGV[0]( $ARGV[1] ) $A->$ARGV[0]( $ARGV[1] ) %{$A->$ARGV[0]( $ARGV[1] ) } eval "$A->$ARGV[0]( $ARGV[1] )"; eval "{$A->$ARGV[0]( $ARGV[1] ) };" $A->\$ARGV[0]( $ARGV[1] )
    and like 27 other varieties. Can you (Rolf of course) suggest a syntax that works here?

    TY!

Use global flag when declaring regular expressions with qr?
6 direct replies — Read more / Contribute
by unmatched
on Oct 28, 2024 at 10:41
    Hello!

    I'm just learning Perl and as an exercise I'm writing a small script that reads a file and outputs every URL it can find. I know there are modules for this, this is just for learning purposes, and to brush up on regular expressions. I came up with the following regular expression:

    my $re = qr( ( (?:[a-z][a-z0-9+-.]*) :// (?: (?: [a-z0-9._~!:;=&'\$\(\)\*\+\-\,]+@ )? (?: \[${ipv6}\] | ${ipv4} | [a-z0-9._~!;=&'\$\(\)\*\+\-\,]+ ) ) ) )xi; foreach ($ARGV[0]) { open my $fh, '<', $_ or die("Error opening file $_.\n"); while (my $row = <$fh>) { chomp $row; next if $row eq ""; if ($row =~ $re) { print "$1\n"; } } close($fh); }

    As you can see, I'm using qr to define the regular expression, as it's composed of other regular expressions defined in the code (omitted here for brevity). This gives me the most flexibility to later on refactor this script to make it more general purpose, or at least that is the idea.

    The file is read line by line, comparing against $re, and correctly printing the first URL it finds on that line. And that's the issue, it only finds the first match even when there are multiple URLs on that line. Typically, this is where I'd use the global flag, except that apparently I cannot use it with qr as I get an error: Unknown regexp modifier "/g".

    I've been reading about this but haven't been able to figure out a way to search the entire line to capture all matches. I tried using the s flag, different delimiters for qr, in case that made any difference, and of course tried modifying $re to use operators like + and *, but without any results.

    So, I don't know if I'm misunderstanding the problem that I need to solve, or I just don't know enough about Perl to use it effectively. I would say the issue is that declaring regular expressions with qr is not what I need for this particular case but I'm just not sure. Any ideas? Thank you!

Exclude files and directories in tarfile for CPAN upload
3 direct replies — Read more / Contribute
by LanX
on Oct 24, 2024 at 18:28
    Hi

    the title says it already, I have a project directory for a distribution which I want to tar.gz for CPAN.

    But it contains backup files, a massive .git dir and a dir with dev stuff (experimental code, etc)

    What's the easiest way to filter them out? Kind of similar to .gitignore?

    ...

    Well while typing this post I found those promising exclude options and will test them out.

    Posting this anyway as an info for the archives ... ¹

    Cheers Rolf
    (addicted to the Perl Programming Language :)
    see Wikisyntax for the Monastery

    ¹) no pun intended :)


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.
  • 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 having an uproarious good time at the Monastery: (3)
    As of 2024-11-05 18:47 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?
      chatterbot is...






      Results (30 votes). Check out past polls.