Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid

Seekers of Perl Wisdom

by gods
on Sep 07, 1999 at 20:28 UTC ( #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. 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
Declaring and checking content of variables with consecutive names
2 direct replies — Read more / Contribute
by rflesch
on Sep 23, 2016 at 07:34
    Dear community,

    in a Perl CGI script, how can I
    (a) declare a set of 100 string variables $str0 .. $str99 in one loop in order to obtain

    my $str0=''; (..) my $str99='';

    (b) further down in the script, find out (in a loop) which of those are empty?

Simple question about sleep function
7 direct replies — Read more / Contribute
by Lucas Rey
on Sep 23, 2016 at 06:29
    Dear community, this is a very simple question, but I cannot found reply.

    Which is the differences between:

    sleep (1);


    select(undef, undef, undef, 1);

    It seems both stop the execution for 1 second. But, is there a real differences for example in term of performance?

    Thank you. Lucas

creating an index of files contents
3 direct replies — Read more / Contribute
by nirelit
on Sep 23, 2016 at 05:35
    hello community,
    Say we have the following structure in our filesystem:
    dir stands for directory of course.
    In dir1, there is a file1.txt that has in it numbers, like below
    876876876876 Same goes for dir2. In dir2, there is a file2.txt, that has in it numbers, like below 6576576
    8768768768765 And so on, with all the rest of the folders. What we need to do, is have a new file (like an index) out of all directories and files values, like below: dir1;6576576,898798789,5645436549,76567576576,876876876876 dir2;6576576,89879878963,56454365492,765675765763,8768768768765 And secondly, another index file, which will have the reverse info 6576576;dir1,dir2 Any ideas on how would you approach this? Best
Implementing methods in a subclass or providing in-place callback: Is it overengineered?
2 direct replies — Read more / Contribute
by Dallaylaen
on Sep 23, 2016 at 05:12

    Hello, dear esteemed monks!

    I just wrote the following in my module. The idea is as follows: allow user to override default methods by either subclassing, or providing a callback. So a subclass with do_foo method and an instance of base class with on_foo member will behave exactly the same.

    However, looking at this again, I suspect it's being overengineered. Should I just provide default do_foo methods in subclass that search for a callback and croak if none found? This will still allow for both ad-hoc overriding and subclassing.

    Should I just go with normal OO and leave do_foo() alone?

    Guess there's no single correct answer after all, but I'd like to hear your opinions and make up my own.

    sub backend_call { my $self = shift; my $method = shift; my $todo = $self->{"on_$method"} || $self->can("do_$method"); if (!$todo) { my $sub = [caller(1)]->[3]; $sub =~ s/.*:://; croak join "", (ref $self || $self),"->",$sub, ": no backend found for $method"; }; return $todo->($self, @_); };

    Thank you!

Can't get a server response from LWP Request
2 direct replies — Read more / Contribute
by ddominnik
on Sep 23, 2016 at 03:45

    First off, regarding Perl and coding in general I have just started to learn so it would be great if you could give me easy to understand/execute answers. Now onto the real problem:

    I'm trying to create a tool for a JIRA server at my workplace. But I can't seem to get a response from the server. I already struggle with the login, which takes a JSON string as a POST request and sends back a JSON string with cookie information. I've tried through the browser and with JavaScript, that somehow works, but Perl gives me a 500 status code response. I've already tried JIRA::REST

    use JIRA::REST; use JSON; my $jira = JIRA::REST->new('https://jira.hostname:PORT/jira', 'myuser' +, 'mypass'); my $request = $jira->POST("/issue/search", undef, { jql=> 'project ~ MYPROJECT and status = closed', starAt=> 0, maxResults=>1, fields=>[asignee], }); print(parse_json ($request));

    Then I tried REST::Client

    use REST::Client; my $client = REST::Client->new(); $client->setHost('https://jira.hostname:PORT/jira/rest'); $client->request('post', '/auth/1/session', ['{ "username" : "myus +er", "password" : "mypass" }', undef]); print ($client->responseContent());

    And now I'm trying a custom request with LWP

    use LWP; use LWP::UserAgent; use HTTP::Request; use JSON; my $host = 'https://jira.hostname:PORT/jira/rest'; my $loginurl = '/auth/1/session'; my %credentials = ("username"=>"myuser", "password"=>"mypa +ss"); my $json = encode_json \%credentials; my $request = HTTP::Request->new('POST', $host.=$loginurl) +; $request -> header('Content-Type'=>'application/json'); $request -> content($json); my $browser = LWP::UserAgent->new; $browser -> agent('Mozilla/5.0'); $browser -> protocols_allowed(['https']); my $response = $browser->request($request); if($response->is_success){ print $response->decoded_content; } else { die $response->status_line; };

    All of them are giving me the same or a similar response:

    500 Can't connect to jira.hostname:PORT Bad file descriptor at C:/myperl/perl/vendor/lib/LWP/Protocol/ +line 47. at line 28.

    I think that the LWP lib might be broken somehow, but I already tried upgrading and reinstalling via CPAN and still got no response. The code from the LWP/Protocol/ file is:

    sub _new_socket { my($self, $host, $port, $timeout) = @_; # IPv6 literal IP address should be [bracketed] to remove # ambiguity between ip address and port number. if ( ($host =~ /:/) && ($host !~ /^\[/) ) { $host = "[$host]"; } local($^W) = 0; # IO::Socket::INET can be noisy my $sock = $self->socket_class->new(PeerAddr => $host, PeerPort => $port, LocalAddr => $self->{ua}{local_address}, Proto => 'tcp', Timeout => $timeout, KeepAlive => !!$self->{ua}{conn_cache}, SendTE => 1, $self->_extra_sock_opts($host, $port), ); unless ($sock) { # IO::Socket::INET leaves additional error messages in $@ my $status = "Can't connect to $host:$port"; if ($@ =~ /\bconnect: (.*)/ || $@ =~ /\b(Bad hostname)\b/ || $@ =~ /\b(certificate verify failed)\b/ || $@ =~ /\b(Crypt-SSLeay can't verify hostnames)\b/ ) { $status .= " ($1)"; } die "$status\n\n$@"; # this is the mentioned "line 47" } # perl 5.005's IO::Socket does not have the blocking method. eval { $sock->blocking(0); }; $sock; }

    I really hoped I could fix this myself as generally solving issues yourself is a great way to learn about the language, but I really don't know what to do anymore. It has to be a problem on the client side, because the server is responding as regular when I'm using JavaScript. Any help would be greatly appreciated!
    P.S: I've always used  use strict; use warnings; as well, so I don't think it has something to do with that

    EDIT: Corion's comment was right, it was a proxy issue as well as a SSL-Certificate issue.

    Thank you for your help Perl Monks!

Counting ID on the basis of batch
2 direct replies — Read more / Contribute
by rohan.mohapatra47
on Sep 23, 2016 at 03:02

    My input file is somewhat like this

    CC225|Rosha|xyz|2221|b1 CC225|Rosha|xyz|2230|b1 CC225|Rosha|xyz|2221|b1 CC225|Rosha|xyz|2221|b1 CC225|Roshw|xyz|2222|b2 CC225|Roshw|xyz|2230|b2 CC222|Roqsha|xyz|2222|b1 CC222|Roqsha|xyz|2244|b1 CC222|Roqsh|xyz|2221|b2 CC222|Roqsh|xyz|2111|b2

    Output will be

    CC225|b1|4|Rosha CC225|b2|2|Roshw CC222|b1|2|Roqsha CC222|b2|2|Roqsh

    It counts ID on the basis of batches & prints it.

    Can someone help?

complex data structures
2 direct replies — Read more / Contribute
by perltux
on Sep 22, 2016 at 21:42
    Hi, I have the following data structure:

    my @AnData; my %AN=(data => \@AnData);

    Now if I want to reference an element of the array @AnData via the hash %AN, I found by trial and error that I have to use: \$AN{data}[0x16]

    Why do I need the extra backslash there?

    I would have thought that $AN{data}[0x16] would already be a reference to the element 16 of array @AnData, as $AN{data} is a reference to the array @AnData. To access the value I would have expected to have to use: $$AN{data}[0x16] instead of $AN{data}[0x16].

    Thanks in advance for any clarification.
    A confused perltux
Perl 5.12.2 Data Structures
5 direct replies — Read more / Contribute
by hennesse
on Sep 22, 2016 at 19:34
    My web host is stuck on Perl 5.12.2 Many of the examples in the 5.24 perldsc just do not work. Like: 5.24 docs sez $thirdList{$itemArea}[$itemId] = [a,b,c] will work, but it doesn't. The push job does though. Need some old geezers to explain "how it used to be done". I'm creating a hash of an array of an array.
    use strict; use warnings; my $itemArea; my $itemPrice; my $itemId; my %thirdList; my $area; my $i; $itemArea = "0188"; $itemId = "0000007777"; $itemPrice = "40"; push @{ $thirdList{$itemArea} }, [ $itemArea, $itemId, $itemPrice ]; $itemArea = "0188"; $itemId = "0000009980"; $itemPrice = "41"; push @{ $thirdList{$itemArea} }, [ $itemArea, $itemId, $itemPrice ]; $itemArea = "0123"; $itemId = "0000008888"; $itemPrice = "50"; push @{ $thirdList{$itemArea} }, [ $itemArea, $itemId, $itemPrice ]; $itemArea = "0123"; $itemId = "0000009999"; $itemPrice = "51"; push @{ $thirdList{$itemArea} }, [ $itemArea, $itemId, $itemPrice ]; hardCodedPrint(%thirdList); sub hardCodedPrint { foreach $area ( keys %thirdList) { for ( $i=0; $i <= 1; $i++ ) { print "THIRD: "; print $thirdList{$area}[$i][0], " - "; print $thirdList{$area}[$i][1], " - "; print $thirdList{$area}[$i][2], "\n"; } } }
    hardCodedPrint() needs help. What I need is something like for (  $i=0; $i <= $# $thirdList{$area}; $i++  )  { But no matter what kind of casts and !@#$%^&* stuff I put in there (like $# @{ $thirdList{$area} }, I get a "$# is no longer supported" type of error - or worse. Any ideas? Thanks - Dave
jQuery issue with Dancer2
5 direct replies — Read more / Contribute
by stevieb
on Sep 22, 2016 at 19:20

    Right off the bat, I am positive this is a jQuery/Javascript issue, but before I ask questions on a forum that isn't Perlmonks, I'm hoping a Perl web monk could help.

    I've got a Dancer2 application that works well. I have a couple code snips without any context, but know for fact that the following returns to the jQuery call either 0 or 1:

    get '/get_aux/:aux' => sub { my $aux = params->{aux}; return _aux_state($aux); }; sub _aux_state { # maintains the auxillary state (on/off) my ($aux, $state) = @_; return $auxs->{$aux}{state} if ! defined $state; $auxs->{$aux}{state} = $state; return $state; }

    Now, in my javascript, I *know* that I receive the proper information. On page load finish, I set up a button (which is a glorified checkbox). It's 'checked' value should be a call back to the Perl code. I've augmented and hacked the jquery code so I can see what's happening. In this code, I call aux_state() to set things up. LINE 1, depicted in comments, alerts undefined. However, while I'm in the aux_state() function itself making the call back to Perl (LINE 2), I get an alert with the expected result:

    $(function(){ var state = aux_state('aux1'); alert(state); // LINE 1 $('#aux1').switchbutton({ checked: aux_state('aux1'), onChange: function(checked){ $.get(host +'/set_aux/aux1/'+ checked, function(state) +{ // ... }); } }); }); function aux_state(aux){ $.get(host +'/get_aux/' + aux, function(state){ alert(state); // LINE 2 return state; }); }

    I'm totally missing something with jQuery me thinks. Can anyone point me in the right direction? This is my first real attempt at writing async jQuery code. If not, I will proceed to ask on SO.

    I'm assuming my newbness in jquery is the issue here particularly with callbacks and returning things. If so, a pointer to a *good* doc would be handy. Even though I'm certain this isn't a Perl issue, I'd rather look at home before I go elsewhere (yep, I've searched online, but couldn't find anything conclusive perhaps because I don't know what to search for).



    update: I'm currently reading this.

Need script help
3 direct replies — Read more / Contribute
by jmckinzie
on Sep 22, 2016 at 13:05
    I have a command whose syntax is:  wspmvdata -s $srv -P sp:$src -t  \@$line -P tp: @ep1 @ep2 I can have as many @servers as I want as long as they fit in a command line (ie limitation) Can you help me figure out how to do this? This is what I have so far.
    #!/usr/bin/perl $pm=""; $srv=srv; $src="D:/Tivoli/bin/lcf_bundle.43100/bin/w32-ix86/inv/SCAN/"; $dst="C:/wansupp"; $file=binfile; $tmpfile="D:/Tivoli/custom/bin/binfile.txt"; $cmd="wspmvdata -s $srv -P sp:$src -t \@$line -P tp: $file"; ## this works but I want to shorten the list to a few test endpoints #@eplist=split(/\n/, `wlsendpts \ | grep End | grep -v tcp3 | gr +ep reg`); @eplist=(1_reg1, 2_reg1, 3_reg1); open(DATA, "<$tmpfile") or die "Can't open data"; @eplist = <DATA>; close (DATA); }
    I basically want to run the one command with @ep,@ep2,@ep3

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.
  • Log In?

    What's my password?
    Create A New User
    and the web crawler heard nothing...

    How do I use this? | Other CB clients
    Other Users?
    Others surveying the Monastery: (6)
    As of 2016-09-25 07:59 GMT
    Find Nodes?
      Voting Booth?
      Extraterrestrials haven't visited the Earth yet because:

      Results (466 votes). Check out past polls.