Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things

Seekers of Perl Wisdom

( #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
Vector manipulation
4 direct replies — Read more / Contribute
by jcklasseter
on Jun 26, 2015 at 14:53
    Hi all. This isn't a very well known module, nor well documented (In my google-ing experience). Any ideas would be appreciated. This is my script:
    #!/usr/bin/perl use strict; use warnings; use Math::Vector::Real; use constant DEG_PER_RAD => 45 / atan2(1, 1); my ( $source, $out ) = qw/ IN OUT /; open my $in_fh, '<', $source or die qq{Unable to open "$source" for i +nput: $!\n}; open my $out_fh, '>', $out or die qq{Unable to open "$out" for outp +ut: $!\n}; #select $out_fh; my @data; push @data, V(split) while <$in_fh>; for my $i ( 0 .. $#data-1 ) { for my $j ( $i+1 .. $#data ) { my $val1 = $data[$i]; my $val2 = $data[$j]; my $comp1 = $val1->[0]; my $comp2 = $val2->[0]; my $vect1 = $val1->[3..5]; my $vect2 = $val2->[3..5]; my $norm = $val1->[0..2]; my $nvect1 = $vect1 - $norm ; my $nvect2 = $vect1 - $norm ; if( $comp1 != $comp2 ){ next;}else{ my $degrees = atan2($nvect1, $nvect2) * DEG_PER_RA +D; print "$degrees\n"; } } }
    In essence, the script reads the input and assigns each line to a vector via the Math::Vector::Real module. My input file is like so:
    2 2 2 5 -2 1 2 2 2 2 7 4 5 2 2 2 7 4
    Which are location coordinates. The first 3 numbers on each line correspond to a point, and the other 3 in the line correspond to a nearby point. The first set will often be identical from line to line. The second set will never repeat between consecutive lines like the first. I'm trying to find the angle between the second set of coordinates between two separate rows, after normalizing them with respect to the first set of coordinates. The script works (via print testing) up until  my $vect1 = $val1->[3..5]; . When I print test here, I get:  2 (And a whole host of other errors that stem from this) I cannot find out how to split the values of a vector off into a new vector like I'm trying to. Does anyone have any ideas? Thanks.
Perl Script in Windows Works, but not in Unix
4 direct replies — Read more / Contribute
by dobster936
on Jun 26, 2015 at 14:33

    Hi, I'm trying to run a perl script that is meant to extract a certain section from numerous text documents. The only thing the script requires of me is to input the read and write directories. In Windows it worked like a charm, though took several minutes to run on a relatively small batch (150) of text files. Later I will be automating this process on a cluster, and need to have it working in a Unix environment. When I do the same process I did on my Windows box on my Mac or on the cluster, perl instantaneously feeds me back the command prompt. On Windows, when I'd mess up I'd get an error message. Something like "No matches". For the time being I have set all permissions to 777 on the directories and files I am using (including the script). I've also ran a simple hello world script and received an output. I even tried using the dos2unix command on the text file to no avail. Below is the beginning of my script I am using:

    #!/usr/bin/perl # Script to extract "item 7" from a 10-K report. # This will write the "good" part of the file to stdout, and will writ +e # a "schema string" on a single line to stderr. $dirtoget="E:\######"; $dirwrite="E:\#####"; opendir(IMD, $dirtoget) || die("Cannot open directory"); @thefiles= readdir(IMD); closedir(IMD); foreach $f (@thefiles) { unless ( ($f eq ".") || ($f eq "..") ) { $fr="$dirtoget$f"; open(FILEREAD, "< $fr"); $f=~s/.txt/.mda/g; $fw="$dirwrite$f"; #print $f1; open(FILEWRITE, "> $fw"); $x=""; while($line = <FILEREAD>) { $x .= $line; } # read the whole file into +one string close FILEREAD;

    And yes, I am using forward slashes when switching to Unix directories. I've tried everything from single-quotes to starting with the root (~). I've also tried changing the shebang to env perl to no effect.

    Also, I got it to the point where the code is running, but it is outputting: # This will write the "good" part of the: No such file or directory It would seem in the comment on line 5, it is trying to analyze "file" even thought it is commented out.

    Update: turns out it was the end of the lines on the script. For some reason I forgot I received the text as an MS Word file (god only knows) and had to convert to txt from MS Word. When I used dos2unix command it got rid of all my line spacing all together for some odd reason. I had to reopen to original docx, save it as a text file and specify to end lines with lf. Thanks for all the time you took helping me today!

how to ftp files from a remote server 1 to server 2?
3 direct replies — Read more / Contribute
by kpofcochin
on Jun 26, 2015 at 13:20

    I need to move a file from server 2 to server 3, but both FTP and SSH should get initiated from server 1.

    S1 (SSH)-> S2 (FTP)-> S3
    file needs to be moved from S2 to S3. but the script running in S1. manually I am able to do it but through perl Net:FTP it is establishing session from server 1 instead of server 2
    my code:
    #!/usr/bin/perl -w use Net::FTP; use Net::SSH::Perl; my($host,$user,$pass) = ("Server2","user_name","password"); my $cmd = "whoami"; my $ssh = Net::SSH::Perl->new($host); $ssh->login($user, $pass); my($stdout, $stderr, $exit) = $ssh->cmd($cmd); my $ftp = $ssh->cmd(Net::FTP->new("Server3", Debug => 0) or die "Canno +t connect to Server3 $@"); $ssh->cmd($ftp->login("user_name",'password') or die "Cannot login ", +$ftp->message); $ssh->cmd($ftp->cwd("/home/tmp") or die "Cannot change working directo +ry ", $ftp->message); $ssh->cmd($ftp->put("file_in_server2") or die "get failed ", $ftp->mes +sage); $ssh->cmd($ftp->quit);
Moving gmail messages with net::imap::simple
1 direct reply — Read more / Contribute
by anonymonk
on Jun 26, 2015 at 12:59

    I am trying to move folders to an "old_messages" folder after i have read and stripped the attachments from them but when i do it all of the messages it sends to the "old_messages" folder are blank and from "unknown sender" and the inbox is unchanged I checked around and nobody seems to have had this problem before (p.s. I graduated college a month ago during which i didn't even touch Perl and now i have been working with it for a whole 3 weeks so i apologize if this seems like an obvious fix).

    use strict; use warnings; # required modules use Net::IMAP::Simple; use Email::MIME; use IO::Socket::SSL; use Email::MIME::Attachment::Stripper;
    ###IMAP connecting here### my $nm = $imap->select('INBOX'); for ( my $i = 1 ; $i <= $nm ; $i++ ) { if (!$imap->seen($i) ) { next; } else { my $es = Email::MIME->new( join '', @{ $imap->get($i) } ); my $text = $es->body; my $stripper = Email::MIME::Attachment::Stripper->new($es); my @attachments = $stripper->attachments; my $l = 0; foreach $_(@attachments) { my $url = ""; my $fh = IO::File->new(); open($fh, '>', "$filepath"."$_->{filename}"); binmode($fh); print $fh "$_->{payload}\n"; $fh->close; } $imap->put( 'OLD_MESSAGES', $es, "") or warn $imap->errstr; } }
Installing File::LibMagic with Strawberry Perl
2 direct replies — Read more / Contribute
by jbodoni
on Jun 26, 2015 at 12:40
    For many, their initial response will be to change my environment. If I could get this working in a LAMP environment, I would.. but I'm stuck with Windows 7, IIS, and Strawberry Perl.

    Per the documentation, I've downloaded file 4.x or file 5x and the associated libmagic library and headers ( What I don't know is what to do with those files. If anyone has managed to successfully get this working in this type of environment, I'd like to hear from you.

    Thank you.

XML Parsing from URL
4 direct replies — Read more / Contribute
by jshank
on Jun 26, 2015 at 11:02

    I need to parse a continuous XML stream coming from a device via http. The problem I run into is I can't find a way to convince PerlSAX to take a URL as a source. There's no good way to "download" the XML and hand it off to the XML parser because the download is never going to finish (continuous stream).

    # This is the URL that streams alerts such as motion detection. Docume +ntation at my($url) = "http://".$user.":".$password."@".$ip.":".$port."/ISAPI/Eve +nt/notification/alertStream"; #start an instance of SAX parser for each monitor my $handler = SAXAlertStreamHandler->new(); my $parser = XML::Parser::PerlSAX->new( Handler => $handler ); my %parser_args = (Source => {SystemId => $url}); $parser->parse(%parser_args); exit; Couldn't open http://user:password@ +ion/alertStream: No such file or directory at /usr/local/share/perl/5.18.2/XML/Parser/P line 146.
defined class variable with Moose
2 direct replies — Read more / Contribute
by Hosen1989
on Jun 26, 2015 at 10:05

    defined class variable with Moose

    Dear ALL,

    I need to add array of data to my class (using Moose) and be able to read it inside me class, I thinks something like this:

    here I many use different @parserArray_type_xx with each different file depend on its type to parse it.

    so my Q is: How to do it?


    As my question here was not clear,let me ask again: but what i need to do is to define variable in my class that contain some predefined data (mix of array/hash/scalar/code).



    package DataDecoder; use Moose; ... #######need to add something like this####### my @parserArray_type_01 = ( ... { name => 'YEAR', type => 'CHAR', len => 2, description => sub{0} }, { name => 'MONTH', type => 'CHAR', len => 2, description => sub{0} }, { name => 'DAY', type => 'CHAR', len => 2, description => sub{0} }, { name => 'HOUR', type => 'CHAR', len => 2, description => sub{0} }, { name => sub{ my $data = uc shift; my %SUD_DATA = ('98' => 'TYPE1', '64' => 'TYPE2'); ); (defined $SUD_DATA{$data})? $SUD_DATA{$data} : $data # $data }, type => 'HEX', len => 1, description => sub{ my $data = uc shift; my %SUD_DATA = ('98' => 'TYPE1', '64' => 'TYPE2'); (defined $SUD_DATA{$data})? $SUD_DATA{$data} : $data # $data }, } ); ...
Cannot connect to SMTP Server from Windows 8.1 Pro x64
No replies — Read more | Post response
by sursan
on Jun 26, 2015 at 09:47

    I have recently installed my new computer with Windows 8.1 Pro (x64) in a Windows domain with Strawberry Perl 5.22.0 (with all the updates for Email::* packages)

    I cannot connect to my SMTP server anymore (with SSL). I have the same problem on a Windows 7 Pro (x64) computer in the same domain.

    I used to use ChilKat e-mail on the Windows 7 computer with Strawberry 5.16, but for some reason the perl interpreter crashes now on both computers (with Strawberry 5.16 or newer).

    UPDATE: The code below works in fact on Windows 7 computer with Strawberry Perl 5.16.2 ...

    Here is the code (of course, I have replaced some sensitive data :) ):
    #!/usr/bin/perl use strict; use warnings; use Email::Sender::Simple qw(sendmail); use Email::Sender::Transport::SMTPS; use Email::Simple::Creator; my $transport = Email::Sender::Transport::SMTPS->new( host => '', port => 465, ssl => 'ssl', sasl_username => 'me', sasl_password => 'mypasswd', debug => 1 ); my $message = Email::Simple->create( header => [ From => 'Me <>', To => 'Me <>', Subject => "Simple Test", ], body => "Simple test body", ); try { sendmail($message, { transport => $transport }); } catch { die "Error sending email: $_"; };
    The output is this:
    W:\Development\Eclipse\FIM Send UE Data Status>perl Net::SMTPS>>> Net::SMTPS(0.04) Net::SMTPS>>> IO::Socket::INET6(2.72) Net::SMTPS>>> IO::Socket(1.38) Net::SMTPS>>> IO::Handle(1.35) Net::SMTPS>>> Exporter(5.72) Net::SMTPS>>> Net::SMTP(3.06) Net::SMTPS>>> Net::Cmd(3.06) Net::SMTPS>>> IO::Socket::IP(0.37) DEBUG: .../lib/Net/ global error: Socket has no fileno unable to establish SMTP connection Trace begun at C:\Strawberry\perl\site\lib\Email\Sender\Transport\SMTP line 98 Email::Sender::Transport::SMTPS::_throw('Email::Sender::Transport::SMT +PS=HASH(0x5bc488)', 'unable to establish SMTP connection') called at +C:\Strawberry\perl\site\lib\Email\Sender\Transport\ line 60 Email::Sender::Transport::SMTPS::_smtp_client('Email::Sender::Transpor +t::SMTPS=HASH(0x5bc488)') called at C:\Strawberry\perl\site\lib\Email +\Sender\Transport\ line 107 Email::Sender::Transport::SMTPS::send_email('Email::Sender::Transport: +:SMTPS=HASH(0x5bc488)', 'Email::Abstract=ARRAY(0x494ce8)', 'HASH(0x2c +52658)') called at C:\Strawberry\perl\vendor\lib\Email\Sender\Role\Co line 45 Email::Sender::Role::CommonSending::try {...} at C:\Strawberry\perl\v +endor\lib\Try\ line 77 eval {...} at C:\Strawberry\perl\vendor\lib\Try\ line 72 Try::Tiny::try('CODE(0x2e50960)', 'Try::Tiny::Catch=REF(0x2e3af40)') c +alled at C:\Strawberry\perl\vendor\lib\Email\Sender\Role\CommonSendin line 58 Email::Sender::Role::CommonSending::send('Email::Sender::Transport::SM +TPS=HASH(0x5bc488)', 'Email::Abstract=ARRAY(0x494ce8)', 'HASH(0x2e507 +c8)') called at C:\Strawberry\perl\vendor\lib\Email\Sender\ +line 119 Email::Sender::Simple::send_email('Email::Sender::Simple', 'Email::Abs +tract=ARRAY(0x494ce8)', 'HASH(0x2c54358)') called at C:\Strawberry\pe +rl\vendor\lib\Email\Sender\Role\ line 45 Email::Sender::Role::CommonSending::try {...} at C:\Strawberry\perl\v +endor\lib\Try\ line 77 eval {...} at C:\Strawberry\perl\vendor\lib\Try\ line 72 Try::Tiny::try('CODE(0x2c52688)', 'Try::Tiny::Catch=REF(0x2c2af30)') c +alled at C:\Strawberry\perl\vendor\lib\Email\Sender\Role\CommonSendin line 58 Email::Sender::Role::CommonSending::send('Email::Sender::Simple', 'Ema +il::Simple=HASH(0x2c526d0)', 'HASH(0x2c4ec30)') called at C:\Strawber +ry\perl\vendor\lib\Sub\Exporter\ line 18 Sub::Exporter::Util::__ANON__('Email::Simple=HASH(0x2c526d0)', 'HASH(0 +x2c4ec30)') called at line 29
    Can anybody help me understand where the problem might be? Thank you in advance!
use of uninitialized value in hash element problem
3 direct replies — Read more / Contribute
by mrityunjaynath
on Jun 26, 2015 at 07:33

    Hello everyone ....i have a written a code where i would take up the value form a config.txt file and use those value further. The code is working fine but every time it runs along with the correct output it is also giving some warning like

    use of uninitialized value $key in hash element at line 85, <$CFILE> line 3

    my config.txt file reads like this


    the code portion is here with and line 85 being marked *****

    my $cChipId; my $cSubVersId; my %data_ids; my $readline; open (my $CFILE,"config.txt" ) || die "couldnt open file: $!"; while ($readline = <$CFILE>) { chomp $readline; my ($key , $value) = (split /::/, $readline); $data_ids{$key} = $value; ***** } close($CFILE); for my $key (keys %data_ids) { $cChipId = $data_ids{'chipid'}; $cSubVersId = $data_ids{'subversid'}; }
    please put some light as i am not able to solve this

Code hiding in Perl
5 direct replies — Read more / Contribute
by sumanta
on Jun 26, 2015 at 03:23

    I have been working on to find a solution to hide the business logic of a Perl code so that the project can be delivered to the customer network without much concern. Ofcourse I am sure that it's almost impossible to completely secure the code from "too curious" eyes, but I tried to make things harder for them. Now I need your thoughts/suggestions/criticism for the below mentioned approach.

    I have developed 2 different executable using C programming language. (i) The first program is responsible for encrypting the Perl code with password protected custom encryption logic. This will also modify the Perl script to change Shebang line (to include custom perl intertreter) and add another BEGIN block which restricts use of default Perl interpreter & debugger. (ii) The second program (namely myPerl.exe) has actualy replaced the original "Perl.exe" interpreter. It is responsible for decrypting the encrypted Perl code and perform an in-memory execution. Now the password can be stored in a scattered way inside the encrypted Perl code. It will also restrict the debug mode so that the code can not be viewed. Although the debugging can be performed by providing a password.

    I have implemented this already and it's working fine. During the time of execution it is expected to decrypt the code, so it slightly increases the execution time, but I have no problem with that. I will be very happy to receive your valuable feedback/suggestions on this approach. Thanks in advance.

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!
  • 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 imbibing at the Monastery: (5)
    As of 2015-06-30 05:22 GMT
    Find Nodes?
      Voting Booth?

      What kind of chocolate gives you the most pleasure?

      Results (777 votes), past polls