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 msg file
3 direct replies — Read more / Contribute
by shylaja
on Aug 27, 2014 at 00:43

    Hi, I have a folder with msg files. How to read each msg file in that particular folder and get the body of the mail?

Hygienic eval of templates with perl code?
No replies — Read more | Post response
by LanX
on Aug 26, 2014 at 23:28
    Hi

    I have the feeling of reinventing the wheel and would like to see other solutions...

    I'm evaling code text which is composed of 2 snippets which are supposed to be correct in isolation.

    Take as example using B::Deparse to back engineer a functions code and then wrapping new code around it before evaling. (something like this is shown in the Perl Hacks book)

    Now this additional code could contain new symbols (identifiers) like variables, subnames or labels which might shadow equally named symbols in the original code.

    This is known as Hygiene Problem.

    I decided to solve this with a template system where new symbols need to be placeholders, which are changed (extended with a suffix) if they conflict with old symbols.

    Did anybody already try to solve this on CPAN?

    I'd like to compare different approaches.

    Cheers Rolf

    (addicted to the Perl Programming Language and ☆☆☆☆ :)

beginner's question
3 direct replies — Read more / Contribute
by perl_Gu
on Aug 26, 2014 at 16:42

    a new user and perl-learner, very beginner. I tried to run this this simple program :

    #!/usr/bin/perl-w use strict; $name = "bug"; print "hello there , $name, did you know 1+0", 1+0, "?\n";

    ---- but I got this :

    BEGIN not safe after errors--compilation aborted at /System/Library/Pe +rl/5.16/Carp/Heavy.pm line 3. Compilation failed in require at /Users/Gucci/Downloads/TextMate.app/C +ontents/SharedSupport/Bundles/Perl.tmbundle/Support/exception_handler +.pm line 30.

    I tried other simple codes, but keep getting this, any idea and suggestion , thanks

Passing Along Arrays
2 direct replies — Read more / Contribute
by Perl_Ally
on Aug 26, 2014 at 16:16

    Hello!

    Help greatly appreciated.

    I have the following code:

    sub extractData { my @projects; push( @projects, [readOnly("$proj Data.txt"), "A"] ); unless( $pointerProj eq "NONE" ) { push( @projects, [readOnly("$pointerProj Data.txt"), "B"] ); } for( @projects ) { my @data = @{ $_[0] }; my $key = $_[1]; ... } } sub readOnly { my @contents; my $filePath; my $file; my $errMsg; $filePath = "$path\\" . $_[0]; $errMsg = "Unable to read $filePath: $!"; open $file, '<', $filePath or die $errMsg; @contents = <$file>; close $file; return @contents; }

    My problem is that I'm not correctly passing the resultant array from readOnly() through the anon array pushed in to @projects to ultimately store and use it as @data inside the for-loop.

    The error message I'm getting is "Can't use an undefined value as an ARRAY reference at (the first line inside the for-loop)".

    If someone could provide me with the correct syntax and the rationale behind it I would be much obliged.

    Thanks!

OLE syntax question
1 direct reply — Read more / Contribute
by zuma53
on Aug 26, 2014 at 15:31
Getting XML to text
2 direct replies — Read more / Contribute
by chuck882
on Aug 26, 2014 at 15:16

    Hello, I am lost and looking for guidance. From a PERL Web Service server I simply want to get the XML sent to the server from the other system and get it into a text variable. I cannot seem to find a means to do that. I see where SOAP::SOM lets you parse SOAP responses to web services but I want to do this on the server end and jsut grab the whole XML message. Can anyone point me to a means to do this?

    I do have stub programs working to both send (client) and receive (server) the message.

    Thanks, Chuck

sorting hash of array of hashes by value
3 direct replies — Read more / Contribute
by Special_K
on Aug 26, 2014 at 14:21

    I have the following data structure:



    $data_hash{$key0}[$idx0]{$key1} = <some floating point value>


    I would like to sort this data structure by its values. Currently I am doing this by creating a new hash in which the key is the floating point value, and the value is an array where each element is a concatenation of $key0, $idx0, and $key1. Each value of the new hash has to be an array as opposed to a scalar because the floating point values in the original data structure are not guaranteed to be unique; that is two entries in the original hash of array of hashes could have the same value.

    Is there a way to sort this data structure by value without having to create a new hash first? I figure there must be some way to use the sort command with the original data structure, but I can't seem to get it to work. Also if there is a way to sort my original data structure by value using a single sort command, are there any performance implications by doing so compared to the method I am currently using?

    Here is the method I am currently using if anyone is curious:



    # create a new hash where the key is the value of the original hash, a +nd the value is an array of keys from the original hash that have the + given value foreach $key0 (keys(%data_hash)) { foreach $key1 (keys(%{$data_hash{$key0}})) { for ($i = 0; $i < @{$limit_hash{$key0}{$key1}{'limit'}}; $i++) { push(@{$new_hash{$data_hash{$key0}[$i]{$key1}}}, $key0 . " +__" . $limit_hash{$key0}{$key1}{'limit'}[$i] . "__" . $key1); } } } # now print the new hash that is sorted by value foreach my $sorted_by_val ( sort{$a <=> $b} keys(%new_hash)) { printf("key %.2f: ", $sorted_by_val); foreach my $val (@{$new_hash{$sorted_by_val}}) { printf("$val"); } printf("\n"); }
How to see WWW:Mechanize request headers
2 direct replies — Read more / Contribute
by Anonymous Monk
on Aug 26, 2014 at 12:25

    Hi Monks,

    How can I see the request headers for Perl mechanize get? I am getting the response headers but I need to verify the request also. How ca I get this.

    Thanks in advance.

How to make ajax requests in Dancer2
2 direct replies — Read more / Contribute
by fishmonger
on Aug 26, 2014 at 12:03

    I'm just starting out learning how to use the Dancer2 framework and I'm having problems with figuring out how to configure the route to display the returned data with or without the use of the Dancer2::Plugin::Ajax module.

    For my initial test the route simply returns "ajax test" but the goal is to return the results of a DB query.

    package Templar; use DBI; use Dancer2; #use Dancer2::Plugin::Ajax; use Dancer2::Plugin::Database; use Template; use HTML::Escape qw/escape_html/; use Crypt::SaltedHash; use Data::Dumper; our $VERSION = '0.1'; hook before => sub { if (!session('logged_in') && request->dispatch_path !~ m{^/login}) + { return forward '/login', { requested_path => request->dispatch +_path }; } }; #ajax '/p_details' => sub { "ajax test" }; get '/p_details' => sub { "ajax test" };

    If I use the ajax route, I get a "404 Not Found" error for the p_details page/route.

    The p_details.tt template is:

    <script> $(document).ready(function() { $("#folder").find("[id^='tab']").hide(); // Hide all content $("#tabs li:first").attr("id","current"); // Activate the first ta +b $("#folder #tab1").fadeIn(); // Show first tab's content $('#tabs a').click(function(e) { e.preventDefault(); if ($(this).closest("li").attr("id") == "current"){ //detectio +n for current tab return; } else{ $("#folder").find("[id^='tab']").hide(); // Hide all content $("#tabs li").attr("id",""); //Reset id's $("#tabs li").removeAttr("id"); $(this).parent().attr("id","current"); // Activate this $('#' + $(this).attr('name')).fadeIn(); // Show content for +the current tab } }); partner_details('general'); }); </script> <span id="top"> <h2>Partner Details</h2> <h3>The partner details function is still in development and is not ye +t ready to be used.</h3> </span> <ul id="tabs"> <li><a href="#" onclick="partner_details('general')">General</a></li +> <li><a href="#" onclick="partner_details('qualifier')">EDI Qualifier + / ID</a></li> <li><a href="#" onclick="partner_details('certificates')">Certificat +es</a></li> <li><a href="#" onclick="partner_details('contact')">Contact Informa +tion</a></li> <li><a href="#" onclick="partner_details('notes')">Notes</a></li> </ul> <div id="folder"> </div>

    The javascript is:

    function partner_details(catagory) { if (! xmlHttpObj) { init_ajax(); } if (xmlHttpObj) { var url = '/p_details'; xmlHttpObj.open('GET', url, true); xmlHttpObj.onreadystatechange = partner_tab(catagory); xmlHttpObj.send(null); } } function partner_tab(tab) { var details = { general: "tab1", qualifier: "tab2", certificates: "tab3", contact: "tab4", notes: "tab5" }; //alert(details[tab]); // status is always 0 //alert('response status:' + xmlHttpObj.status); // xmlHttpObj.responseText is always empty //document.getElementById('folder').innerHTML = xmlHttpObj.respons +eText; // this updates the div as expected //document.getElementById('folder').innerHTML = "<table><tr><td>" ++ details[tab] + "</td></tr></table>"; if (xmlHttpObj.readyState == 4 && xmlHttpObj.status == 200) { // we never reach this point alert(details[tab]); document.getElementById('folder').innerHTML = xmlHttpObj.respo +nseText; //document.getElementById('folder').innerHTML="<table><tr><td> +" + details[tab] + "</td></tr></table>"; } }

    Firebug shows that the status is "200 ok", Content-Type is "text/html", Content-Length is 9, and both Response and HTML show the expected "ajax test", but javascript readystate and status never change so the updating of the div or the alert window never take place.

    My first thought was that I had an error in the javascript, but it works correctly in a php app. So, that means that I'm doing something wrong in the route but the Dancer2 documentation in the ajax/jquery area is almost non existent so I haven't been able to figure out the proper syntax.

Fetch the regex matched values from file and write it to a file in line by line format.(Using HPNA to execute the script)
1 direct reply — Read more / Contribute
by bks
on Aug 26, 2014 at 11:40

    Hi,

    I'm executing a command and getting the output as mentioned below. I'm redirecting this output to a file and trying the get the first column of the output and put it in a different file.

    However on execution of script through Cisco Network Compliance Manager/ HP Network Automation Tool. Opened the file where output is written and found that output is in garbled format(not in line by line format).

    I need to pull the first column i.e. filenames and put it in a different file in line by line format. I thought of regex and wrote it to pull the filename but not sure how to fetch the matched values from a file. Regex: (.)((A-Za-zA-Za-z0-9_*))(.*)(\.PEM|m|r|y|t)

    Please guide me.

    Garbled Output will somewhat look this in the file

    ********************************

    show crypto file[] 2FAWWW-2013.PEM 1675 PEM Yes KEY Apache-Portal_2012.pem 1675 PEM Yes KEY Onlineapply-creditcards-Portal-cer 2476 PEM Yes CERT Onlineapply-creditcards-Portal-key 1675 PEM Yes KEY Onlineapply_CC_prxy_1_2013.cer 2520 PEM Yes CERT Onlineapply_CC_prxy_2013.cer 2488 PEM Yes CERT

    ********************************

    If written in line by line format then output will be as follows

    ********************************

    2FAWWW-2013.PEM 1675 PEM Yes KEY

    Apache-Portal_2012.pem 1675 PEM Yes KEY

    Onlineapply-creditcards-Portal-cer 2476 PEM Yes CERT

    Onlineapply-creditcards-Portal-key 1675 PEM Yes KEY

    Onlineapply_CC_prxy_1_2013.cer 2520 PEM Yes CERT

    Onlineapply_CC_prxy_2013.cer 2488 PEM Yes CERT

    ********************************

    Want to use the regex and print the filenames/column1 in different file in line by line format as below

    ********************************

    2FAWWW-2013.PEM

    Apache-Portal_2012.pem

    Onlineapply-creditcards-Portal-cer

    Onlineapply-creditcards-Portal-key

    Onlineapply_CC_prxy_1_2013.cer

    Onlineapply_CC_prxy_2013.cer

    ********************************

    Code used in NCM/HPNA Tool

    #!/usr/bin/perl use strict; use warnings; use Getopt::Long; use Opsware::NAS::Connect; my($host,$port,$user,$pass) = ('localhost','$tc_proxy_telnet_port$','$ +tc_user_username$','$tc_user_password$'); my $device = '#$tc_device_id$'; my @output; my $con = Opsware::NAS::Connect->new(-user => $user, -pass => $pass, - +host => $host, -port => $port); $con->login(); $con->connect( $device ) or die "Failed to connect."; $con->cmd("terminal length 0"); print "show crypto files \n"; open my $fh, ">cryptofiles.log" or die "Cant open file died unexpected +ly"; @output = $con->cmd("show crypto files"); foreach (@output) { print $fh $_; } close $fh; $con->disconnect(); $con->logout(); undef $con; exit(0);

    Thanks!


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!
  • 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
  • Outside of code tags, you may need to use entities for some characters:
            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.