Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot

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
Device::SerialPorDevice::SerialPort;t Problem
2 direct replies — Read more / Contribute
by kurta
on Apr 30, 2016 at 14:25

    This is a weird one. I'm reading data from a GPS module. The following code gives the expected response:

    #! /opt/local/bin/perl -w use strict; require 5.000; use lib "/opt/local/lib/perl5/"; use Data::Dump qw(dump); use Device::SerialPort; my $port = Device::SerialPort->new("/dev/tty.usbserial"); $port->are_match("\r\n"); $port->baudrate(9600); $port->databits(8); $port->parity("none"); $port->stopbits(1); while (1) { my $s = $port->lookfor(); next if $s eq ''; print $s,"\n"; if ($s=~/.*GPGGA.*/){ my @a=$s=~/(\d+\.\d{2}),(\d+\.\d+),(N|S),(\d+\.\d+),(E|W)/; print "==",dump(@a); } }
    But if I comment out the "print $s,"\n";" statement, I get nothing. Here's some sample output:

    ==("108746.88", "2048.37808", "N", "80113.44007", "W")$GPGSA,A,3,16,26,22,31,23,27,51,80,89,,,,1.78,1.82,1.36*83

    I suspect there's something strange going on with buffering, but don't understand why printing a variable should make a difference. Any perl-ly wisdom would be appreciated

    === ARGH! Just added a "/n" to the print "==",dump(@a); line and now it works. Why doesn't the buffer flush on print? Is Device::SerialPort resetting something?
Increment frequency of attempts based on IP and login details combination
3 direct replies — Read more / Contribute
by firepro20
on Apr 30, 2016 at 04:36

    I have the following logfile

    2016-04-29 15:56:48+0000 [cowrie.ssh.transport.HoneyPotSSHFactory] New + connection: ( [session: 3b8d22b +5] 2016-04-29 15:56:49+0000 [SSHService ssh-userauth on HoneyPotTransport +,28,] login attempt [root/root] succeeded 2016-04-29 16:11:14+0000 [cowrie.ssh.transport.HoneyPotSSHFactory] New + connection: ( [session: a6c0fac1] 2016-04-29 16:17:42+0000 [cowrie.ssh.transport.HoneyPotSSHFactory] New + connection: ( [session: d33e1566] 2016-04-29 19:07:10+0000 [cowrie.ssh.transport.HoneyPotSSHFactory] New + connection: ( [session: fafec37 +d] 2016-04-29 19:07:10+0000 [SSHService ssh-userauth on HoneyPotTransport +,0,] login attempt [root/root] succeeded 2016-04-29 19:42:58+0000 [cowrie.ssh.transport.HoneyPotSSHFactory] New + connection: ( [session: 539960a +3] 2016-04-29 19:42:58+0000 [SSHService ssh-userauth on HoneyPotTransport +,1,] login attempt [root/root] succeeded 2016-04-29 20:39:03+0000 [cowrie.ssh.transport.HoneyPotSSHFactory] New + connection: ( [session: b9f550d +f] 2016-04-29 20:39:03+0000 [SSHService ssh-userauth on HoneyPotTransport +,2,] login attempt [root/root] succeeded 2016-04-29 21:13:41+0000 [cowrie.ssh.transport.HoneyPotSSHFactory] New + connection: ( [session: e696835c] 2016-04-29 21:13:59+0000 [SSHService ssh-userauth on HoneyPotTransport +,3,] login attempt [user1/test123] failed 2016-04-29 21:14:10+0000 [SSHService ssh-userauth on HoneyPotTransport +,3,] login attempt [user1/test1234] failed 2016-04-29 21:14:13+0000 [SSHService ssh-userauth on HoneyPotTransport +,3,] login attempt [user1/test123] failed

    I want to increment a value called frequency whenever the IP is found and the same username and password are used to login. For that I want to output the SourcePort, the statusfailed/succedded and the total number of occurrences of the IP, and user/pass combination. So for instance, taking the last three entries, the result would be

    Port,Status,Occurrences 64400,failed,2 64400,failed,1

    This is the code I have so far

    $ip = ""; $port = ""; $usr = ""; $pass = ""; $status = ""; $frequency = 0; #Given this is a user/pass attempt honeypot logger, I will use + a wide character to reduce the possibility of stopping #the WEKA CSV loader from functioning by using smileyface as s +eperators. while(my $lines = <LOG2>){ if($lines =~ /New connection/){ ($ip, $port) = (split /[\[\]\s:()]+/, $lines)[7,8]; } if($lines =~ /login attempt/){#and the ip of the new c +onnection if($lines =~ /$ip/){ ($usr, $pass, $status) = (split /[\s:\[\]\/]+/, $lines +)[-3,-2,-1]; if($lines =~/$ip/ && $lines =~/$usr/ && $lines + =~ /$pass/){ $frequency++ } if($ip && $port && $usr && $pass && $status ne + ""){ print FILE2 join "$seperator",($port, +$status, $frequency, $end); print FILE2 "\n"; } } }

    This was also cross posted on Stack Overflow

Bioinformatics - Scoring DNA mutations
2 direct replies — Read more / Contribute
by allsop_5
on Apr 29, 2016 at 21:28

    Hi all, I'm doing an assignment that requires I shuffle a DNA sequence, then score the "mutations" according to a set of rules. I have come up with the below code and it is obviously not working (gives really odd results, like -2-4-400-200...etc) I'm hoping I just did something silly. My intent was to create a foreach loop that would use the subroutine I have that has a hash that creates numeric values based on evaluating the keys (hopefully that makes sense). Here is the code:

    my $score; foreach(0 .. length($string) - 1){ my $s = substr($string, $_, 1); my $m = substr($shuf_seq, $_, 1); $score = scoring($s, $m); $score += $score; print $score; } print "\nThis is the total mutation score: $score \n"; #sub to calculate the scoring of mutations #If purine --> purine: -1 #If pyrimidine --> pyrimidine: -1 #If purine --> pyrimidine (or vice versa): -2 #If no change: 0 sub scoring{ my ($a, $b) = sort @_; my %scores; $scores{'A'}{'G'} = -1; $scores{'A'}{'T'} = -2; $scores{'A'}{'C'} = -2; $scores{'G'}{'T'} = -2; $scores{'C'}{'G'} = -2; $scores{'C'}{'T'} = -1; $scores{'A'}{'A'} = +0; $scores{'T'}{'T'} = +0; $scores{'C'}{'C'} = +0; $scores{'G'}{'G'} = +0; return $scores{$a}{$b}; }
DBIx::Class Looping thru resultset
2 direct replies — Read more / Contribute
by phildeman
on Apr 29, 2016 at 16:04

    Hi All,

    Can variables be used in place of column names when looping through DBIx::Class array of objects.
    For example:

    my @db_colnames = ('lastname','firstname','middlename'); my @rows = $schema->resultset( 'myTable' )->search({}, {order_by => [qw +/ lastname firstname middlename /] } ); foreach my $row (@rows) { foreach my $col (@db_colnames) { print $row->$col ."\t"; } print "\n"; }

    No value printed. However, when I used the actual column name to retrieve the data, it worked fine. For example:

    . . print $row->lastname . "\t" . $row->firstname . "\t" . $row->middlenam +e . "\t"; print "\n"; . .

    Thanks for your help.

Using Positions from one array to find the value in the same position of another.
3 direct replies — Read more / Contribute
by RuZombieSlayer
on Apr 29, 2016 at 15:41

    Hello, I want to use the values from one array to search for positions in another and return what was found at those positions, the code below may give you and idea of what i am trying to achieve. Basically input a sentance and have each word turned into a 6 digit number to show that words position in an array then find the value of something in another array at the same position. I am new to pearl have been learning for a few weeks. I am teaching my self and am hoping to learn through this project i have set myself. Sorry if the code is a bit sloppy or not as sleek as it could be.

    use stict; use warnings; my @words = ("a", "abbey", .. "zymophore", "zymophoric"); #in reality, this is a list of all words in the english #language apro +ximatly 400,000 words long my $sentance = <>; my @sentanceSplit = split(' ', $lcsentance); #all words need to be lower case #for simplicity, say we type "a zymophoric". my @indexes; foreach my $place (@sentanceSplit) { push @indexes, sprintf '%06d', first_index { $_ eq $place } @words +; }; #because of our input, @indexes will print 000000 399999 #because 'a' is in the 0th position of @words therfore #000000 #and 'zymophoric' is in the 400 thousandth position #retuning 399999 my @numbers2 = ("250690", "004058", ..); #400,000 numbers but in a random order instead of #(0..399999) #my goal now is to take the values from @indexes and #compare them to +@numbers2 and say (values of @indexes are #0 399999) notice we remove + the leading zeros. Then look #for what is foreach in the oth positio +n of @numbers2 ie. #"250690" and the 399999th position returning what +ever it #finds lets say 000001 #then have my @new = whatever the result is, so ("250690", #"000001");

    I hope i have given you an idea what i am trying to achieve, I am not sure how to achieve this, perhaps hashes? eitherway an example would be very helpful thanks!!

Parse multiline logfile
2 direct replies — Read more / Contribute
by chris2013
on Apr 29, 2016 at 15:04
    Dear All,

    I'd like to parse a Charon (StrongSwan) logfile.

    Somewhere it logs a failed login. If this is found, I'd like to lookup the username and IP address, that are mentioned some lines above.

    What's the best approach? Is there any framework that can do that? Where I only have to fill-in the regex?

    Should I read the whole logfile to an array and then go back? Or is there something like grep? I've tried to use a shell script and let perl one-liners do the regex stuff. Unfortunately I couldn't escape the single quotes in front and after the e-mail address. They have to be quoted because of the shell and the regex. Tried to write them to an evironment variable but that didn't work. Probably, there are completely different and better solutions.

    export MYP="identity '([A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,})'" EMAIL=`grep -B15 "$DATE" $LOGFILE | grep "$CONID" | grep identity | pe +rl -nle 'print "$1" if /$ENV{MYP}/'`


    Apr 29 10:01:10 charon: 07[NET] <con1|33> received pac +ket: from[55842] to[4500] (80 bytes) Apr 29 10:01:10 charon: 14[IKE] <con1|33> received EAP + identity '' Apr 29 10:01:11 charon: 14[IKE] <con1|33> EAP-MS-CHAPv +2 verification failed, retry (1)

    - Chris

Creating pointers in a HoH declaration
3 direct replies — Read more / Contribute
by cmv
on Apr 29, 2016 at 14:38
    Hi Monks-

    I'm a little embarrassed to ask this question, as I feel I should know the answer - however, I haven't been able to come up with a good answer (by searching or thinking) for 2 days! Please help - my mind is going...

    I want to declare a hash-of-hashes, where some of the elements point to each other. Is it possible to do it in a declaration? Here is some code that makes it happen outside the declaration.

    Any help is much appreciated!



    use strict; use warnings; use Data::Dumper; my %fields = ( version1 => { 1 => 'Field 1', 2 => 'Field 2', 3 => 'Field 3', }, version2 => { 1 => 'Field 1', 2 => 'Field 2', 3 => 'Field 3', 4 => 'Field 4', }, version3 => { 1 => 'Field 1', 2 => 'Field 2', 3 => 'Field 3', 4 => 'Field 4', 5 => 'Field 5', }, version4 => { # What if version4 is exactly the same as version3. # How do I just make version4 point to verson3? }, ); print STDERR "fields Dump1:\n", Dumper(\%fields), "\n"; $fields{version4} = $fields{version3}; print STDERR "fields Dump2:\n", Dumper(\%fields), "\n";
Filtering array of strings and numbers
3 direct replies — Read more / Contribute
by nysus
on Apr 29, 2016 at 11:28

    I'm stuck on what I think should be a simple problem. I want to filter out elements from an array. I don't know if they array contains strings or numbers or both. And I don't know if the value I want to filter out is a string or number:

    my $string_or_number; my @filtered = grep { $string_or_number ne $_ } @strings_or_numbers;

    What's the best way to accomplishing this without throwing an error if the wrong equality operator is used?

    $PM = "Perl Monk's";
    $MCF = "Most Clueless Friar Abbot Bishop Pontiff Deacon Curate";
    $nysus = $PM . ' ' . $MCF;
    Click here if you love Perl Monks

Detached forking in a CGI script
4 direct replies — Read more / Contribute
by xylose
on Apr 29, 2016 at 11:06

    I'm having a problem satisfying a number of constraints in a CGI script I'm writing.

    I need the script to fork a child process and to get hold of the pid of this child, but to then not make the parent (the CGI process) wait for the child, and allow it to exit immediately.

    One extra complication is that in the child I exec a new program (an R script), but capture STDOUT and STDERR into log files, so I can't close those filehandles before doing the exec.

    I've tried a number of different approaches, but anything which gives me the pid and starts the child process correctly always makes the parent hang until the child is done.

    My current (not working) best guess is:

    $SIG{CHLD} = 'IGNORE'; my $pid = fork(); if ($pid) { # We're the child and we need to start the analysis # First we'll write out pid into a file in the run # folder so that the results tracker can tell if we've # died. open (PID,'>','pid.txt') or die "Failed to write to pid file : $!" +; print PID $pid; close PID or die "Failed to write to pid file: $!"; exec("Rscript analysis.r > log.txt 2>errors.txt"); exit(0); } print $q->redirect("script.cgi?job_id=$job_id");

    In this version the child runs, but the parent doesn't exit until the child has completed.

    Any ideas how I can have my cake and eat it?


How to upload a file in a test through Open Windows using Selenium::Remote::Driver Perl package
2 direct replies — Read more / Contribute
by Chaoui05
on Apr 29, 2016 at 08:28

    Below are the additional bullets : I can get my "button" with following code :

    $elem = $driver->find_element('//*[@id="file_uploader"]/div/div/div/d +iv[1]/div[1]/div/span'); $driver->mouse_move_to_location(element => $elem); # xoffset => x +, yoffset => y $driver->click_ok('LEFT'); $driver->pause(3000);

    But after that, I can't get anything in Opened Window which appears to upload. How is it possible to upload a file also?

    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!
  • 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 perusing the Monastery: (3)
    As of 2016-05-01 00:24 GMT
    Find Nodes?
      Voting Booth?
      :nehw tseb si esrever ni gnitirW

      Results (441 votes). Check out past polls.