I'm trying to port the following php functionality over to perl:
public function loadKey($mod, $exp, $type = 'public')
{
$rsa = new Crypt_RSA();
$rsa->signatureMode = CRYPT_RSA_SIGNATURE_PKCS1;
$rsa->setHash('sha256');
$rsa->modulus = new Math_BigInteger(Magicsig::base64_url_decode($mod), 256);
$rsa->k = strlen($rsa->modulus->toBytes());
$rsa->exponent = new Math_BigInteger(Magicsig::base64_url_decode($exp), 256);
// snip...
}
I need to convert a string in the form ("RSA.$mod.$exp.$private_exp"):
RSA.mVgY8RN6URBTstndvmUUPb4UZTdwvwmddSKE5z_jvKUEK6yk1u3rrC9yN8k6FilGj9K0eeUPe2hf4Pj-5CmHww==.AQAB.Lgy_yL3hsLBngkFdDw1Jy9TmSRMiH6yihYetQ8jy-jZXdsZXd8V5ub3kuBHHk4M39i3TduIkcrjcsiWQb77D8Q==
...to a Crypt::RSA object. I've split out the components so I have $mod, $exp, and $private_exp, but the perl Crypt::RSA API doesn't seem to have a way to explicitly set.
I have a working perl script that grabs the data I need and displays them to STDOUT, but now I need to change it to generate a data file (csv, tab dellimited, any delimiter file). The regular expression is filtering the data that I need, but I don't want the entire string, just snippets of the output. I'm assuming I would need to store this in another variable to create my output file.
I need a good example of this or suggestions to alter this code. Thank you in advance. :-)
Here's my code:
#!/usr/bin/perl -w
# Usage: ./bakstatinfo.pl Jul 28 2010 /var/log/mybackup.log <server1> <server2>
use strict;
use warnings;
#This piece added to view the arguments passed in
$" = "][";
print "===================================================================================\n";
print "[@ARGV]\n";
#Declare Variables
my($mon,$day,$year,$file,$server) = @ARGV;
my $regex_flag = 0;
splice(@ARGV, 0, 4, ());
foreach my $server ( @ARGV ) { #foreach will take Xn of server entries and add to the loop
print "===================================================================================\n";
print "REPORTING SUMMARY for SERVER : $server\n";
open(my $fh,"ssh $server cat $file |") or die "can't open log $server:$file: $!\n";
while (my $line = <$fh>) {
if ($line =~ m/.* $mon $day \d{2}:\d{2}:\d{2} $year:.*(ERROR:|backup-date=|backup-size=|backup-time=|backup-status)/) {
print $line;
$regex_flag=1; #Set to true
}
}
if ($regex_flag==0) {
print "NOTHING TO REPORT FOR $server: $mon $day $year \n";
}
$regex_flag=0;
close($fh);
}
My working output now:
===================================================================================
[Jul][28][2010][/var/log/mybackup.log][server1]
===================================================================================
REPORTING SUMMARY for SERVER : server1
Wed Jul 28 00:49:54 2010: test203.bak_lvm:backup:INFO: backup-size=417.32 GB
Wed Jul 28 00:49:54 2010: test203.bak_lvm:backup:INFO: backup-time=04:49:51
Wed Jul 28 00:49:54 2010: test203.bak_lvm:backup:INFO: backup-status=Backup succeeded
The output I need to see would be something like this:(data file with separated by ';' for example)
MyDate=Wed Jul 28;MyBackupSet= test203.bak_lvm;MyBackupSize=187.24 GB;MyBackupTime=04:49:51;MyBackupStat=Backup succeeded
I've been thinking about learning Perl. Should I learn Perl5 or start with Perl6?
So, I believe this has something to do with the difference between arrays and lists, but I don't understand what's going on here. Can anyone explain how and why Perl treats an expression like (1..4) differently than (1, 2, 3, 4) and @{[1..4]}?
$ perl -de1
Loading DB routines from perl5db.pl version 1.31
Editor support available.
Enter h or `h h' for help, or `man perldebug' for more help.
main::(-e:1): 1
DB<1> x scalar (1,2,3,4)
0 4
DB<2> x scalar (1..2,3,4)
0 4
DB<3> x scalar (1,2..3,4)
0 4
DB<4> x scalar (1,2,3..4)
0 ''
DB<5> sub foo { (1..4) } # (the actual problem case, except 4 would be a variable)
DB<6> x scalar foo()
0 ''
DB<7> sub bar { @{[1..4]} } # (the workaround)
DB<8> x scalar bar()
0 4
I am trying to split a string with multiple white spaces. I only want to split where there are 2 or more white spaces. I have tried multiple things and I keep getting the same output which is that it splits after every letter. Here is the last thing I tried
@cellMessage = split(s/ {2,}//g, $message);
foreach(@cellMessage){
print "$_ \n";
}
I'm using the Assets plugin in my Catalyst app, and I would like some javascript and css files included in the assets of every page.
My first thought is call $c->assets->include('file.js') from MyApp/lib/MyApp.pm where I do setup and config, but I don't know how to get a hold of $c there.
My next idea involves using the WRAPPER stuff, and placing calls like [% c.assets.include('file.js') %] in default html template, but the calls dump the object information to the page, so the calls would have to be uglied up to suppress output.
Solutions or new ideas appreciated. Thanks in advance.
Hi,
I've the following strings which I would like to decode into different variables depending on the string
examples
{"response":{"report":"fail","brand":"1.0","fail":{"message":"Invalid Number"}}}
{"response":{"report" : "pass", "brand" : "1.0", "payment" :{"paymentId":"4CA008DAAA41EC19C754EF"}}}
{"response":{"report":"fail","brand":"1.0","fail":{"message":"internal server problems."}}}
{"response" : {"report" : "pass", "brand" : "1.0", "email" :{"subject":"Notification","to":"TEST@TEST.COM"}}}
I want to get one liner command or multiple command to fetch values into different variables.
Results
Variable 1 = fail variable 2 = 1.0 variable 3 = Invalid Number
Variable 1 = pass variable 2 = 1.0 variable 3 = 4CA008DAAA41EC19C754EF
Variable 1 = fail variable 2 = 1.0 variable 3 = internal server problems.
variabl 1 = pass variable 2 = 1.0 variable 3 = Notification variable 4 = TEST@TEST.COM ( since there are 2 values in the inner most {} )
I'm totally new to Perl but I'd like to try it out. I read about two rival distributions available for Windows platform (I guess there's just Perl on other OSes :).
Wikipedia says that Strawberry comes with additional dev tools to compile CPAN modules if necessary. Sounds pretty good to me.
It also says that ActivePerl has a lot of prepackaged modules which are easier to install with PPM. Sounds great too!
There's a clear trade-off between those two. And I wonder what should I pick to get started? If I pick one how hard is it to migrate to the other?
I have about 20 CSV's that all look like this:
"[email]","[fname]","[lname]","[prefix]","[suffix]","[fax]","[phone]","[business]","[address1]","[address2]","[city]","[state]","[zip]","[setdate]","[email_type]","[start_code]"
What I've been told I need to produce is the exact same thing, but with each file now containing the start_code from every other file where the email matches.
It doesn't matter if any of the other fields don't match, just the email field is important, and the only change to each file would be to add any other start_code values from other files where the email matches.
For example, if the same email appeared in the wicq.csv, oota.csv, and itos.csv it would go from being the following in each file:
"anon@yahoo.com","anon",,,,,,,,,,,,01/16/08 08:05 PM,,"WIQC PDX"
"anon@yahoo.com","anon",,,,,,,,,,,,01/16/08 08:05 PM,,"OOTA"
"anon@yahoo.com","anon",,,,,,,,,,,,01/16/08 08:05 PM,,"ITOS"
to
"anon@yahoo.com","anon",,,,,,,,,,,,01/16/08 08:05 PM,,"WIQC PDX, OOTA, ITOS"
for all three files (wicq.csv, oota.csv, and itos.csv)
Tools I have available would be OS X command line (awk, sed, etc) as well as perl-though I'm not too familiar with either, and there may be a better way to do this.
I have an input C file (myfile.c) that looks like this :
void func_foo();
void func_bar();
//supercrazytag
I want to use a shell command to insert new function prototypes, such that the output becomes:
void func_foo();
void func_bar();
void func_new();
//supercrazytag
So far I've been unsuccessful using SED or PERL. What didn't work:
sed 's|\n\n//supercrazytag|void func_new();\n\n//supercrazytag|g' < myfile.c
sed 's|(\n\n//supercrazytag)|void func_new();\1|g' < myfile.c
Using the same patterns with perl -pe "....." didn't work either.
What am I missing ? I've tried many different approaches, including this and this and that.
I have a source text in a file and looking for a code that would take the second (or n-th - in general) row from this file and print to a seperate file.
Any idea how to do this?
A perl script that scrapes static html pages from a website and writes them to individual files appears to work, but also prints many instances of wide character in print at ./script.pl line n to console: one for each page scraped.
However, a brief glance at the html files generated does not reveal any obvious mistakes in the scraping. How can I find/fix the problem character(s)? Should I even care about fixing it?
The relevant code:
use WWW::Mechanize;
my $mech = WWW::Mechanize->new;
...
foreach (@urls) {
$mech->get($_);
print FILE $mech->content; #MESSAGE REFERS TO THIS LINE
...
This is on OSX with Perl 5.8.8.
I've been assigned to pick up a webapplication written in some old Perl Legacy code, get it working on our server to later extend it. The code was written 10 years ago by a solitary self-taught developer...
The code has weird stuff going on - they are not afraid to do lib-param.pl on line one, and later in the file do /lib-pl/lib-param.pl - which is offcourse a different file.
Including a.pl with methods b() and c() and later including d.pl with methods c() and e() seems to be quite popular too... Packages appear to be unknown, so you'll just find &c() somewhere in the code later.
Interesting questions:
I'm inclined to go through each file and refactor it, but am not allowed to do that - only the strict minimum to get the code working. (But since the code never uses strict, I don't know if I'm gonna...)
Is there a way to send text messages for free or cheap with Perl? I see a lot of things on CPAN, but they all cost quite a bit. Is there anyway to send an email as a text message?
Ok, here's the deal. I have an array (inputted from a 400 MB file) where if I run the sort() command on it, comp runs out of memory. The input file isn't the problem, so I've decided to break the initial array into smaller arrays that I can perform the sort on. I can break the initial array into arrays of size 100k, which my code does.
(for the purposes of this testing, I've shrank the file from 400 MB to 40 MB)
I run my break array code, and on first iteration, i have an array of 100k as a reference in my @arrayList. My code is just this:
push @arrayList, \@sorted; #@sorted is the sorted version of the 100k array
$temp = @arrayList; #returns 1, which it should
@arrayTemp2 = @{$arrayList[0]};
$temp = @arrayTemp2; #returns 100k, which it should
@arrayTemp2 = @{$arrayList[1]};
$temp = @arrayTemp2; #returns 0 since it is uninitialized
On the next loop in the for loop, the sorted array is the rest of the initial array, only 23k. Same code runs again, with these results:
push @arrayList, \@sorted; #@sorted is the sorted version of the 23k array
$temp = @arrayList; #returns 2, which it should
@arrayTemp2 = @{$arrayList[0]};
$temp = @arrayTemp2; #returns 23301, which is wrong
@arrayTemp2 = @{$arrayList[1]};
$temp = @arrayTemp2; #returns 23301, which is right.
I've tried using every different way I can think of to fix this, and I just have no ideas left. Any help?
Thanks
I have been working on a perl project at work, and came across a strange memory leak. I have boiled down the source of my problem into a contrived example:
#!/usr/bin/perl
use strict;
use warnings;
# takes: an array reference
# returns: 1
sub g {
my ($a) = @_;
return 1;
}
# takes: nothing
# returns: the result of applying g on an array reference
sub f {
my @a = ('a') x 131072; # allocate roughly a megabyte
return g(\@a);
}
# causes a leak:
#map { f($_) } (1..100000);
# loop equivalent to map, no leak:
#my @b;
#for my $i (1..100000) {
# push @b, f($_);
#}
# causes a leak:
#grep { f($_) } (1..100000);
# loop equivalent to grep, no leak:
#my @b;
#for my $i (1..100000) {
# push @b, $i if f($_);
#}
Uncomment 1 of the 4 blocks of code (beneath the subroutines) at a time and run the script while monitoring its memory usage. On my machine, the code that uses grep or map appear to cause memory leaks, whereas the "loop equivalent"s do not. My perl version is v5.10.1, and I am running Ubuntu.
I believe this could be a bug in perl, but I don't want to jump to a drastic conclusion without another opinion on what could be the cause. Can anyone explain if this behaviour is correct?
Thanks
my %geo_location_map = (
US => [ 'US', 'CA' ],
EU => [ 'GB', 'ES' ],
);
$location= "US" ;
my $goahead = 0;
if (exists $geo_location_map{US} ) {
print "exists";
my @glocation = $geo_location_map{US};
foreach @glocation {
if ( $_ eq "$location"} { $goahead=1; last;}
}
}
I tried its not working
Hi, I have a file like:
START
Length: 1432
RIdentifier: 4
VIdentifier: 4
Format: 5
TS number: 9
DHeader
Version = 1
Length = 1432
Command Flags = RPT (0xd0)
Command Code = Accounting-Request (271)
Application Id = Rf-Application (3)
Hop By Hop Id = 51
End To End Id = 8847360
START
Length: 12
RIdentifier: 2
VIdentifier: 4
Format: 5
TS number: 6
DHeader
Version = 1
Length = 1432
Command Flags = RPT (0xd0)
Command Code = Accounting-Request (271)
Application Id = Rf-Application (3)
Hop By Hop Id = 51
End To End Id = 8847360
START
I need to collect all the lines that are found between START and write it into 2 files.
I tried with flip flop in Perl like:
open(FILE, $ARGV[0]);
while (<FILE>) {
if (/START/ .. /START/) {
print "$. $_ \n";
}
}
But I am getting only the lines that have START. Could you please help me?
I wanted to find out just how big the differences in speed was between popular languages. To benchmark the languages I choose a very simple but common operation to be performed in similar conditions with different languages. The results came as quite a surprise.
Method
To do this benchmark I made simple Hello World programs in the different languages (some compiled, some interpreted). I then wrote a simple wrapper in Perl that ran the programs in a for-loop, simulating running the program 1000 times. This method may be a testament to how well my ubuntu fires different executables and frameworks and not to the code, but it is still interesting to see how a real world application of a program language is to do a menial task like printing a string many times. To eliminate the graphics-card I piped the output of the programs to a file in one instance and did nothing with it in another instance (just back-ticking the output to a perl-variable and then doing nothing to it). Before claiming that the methodology is unfair I would like to point out that this is the way I run programs on linux/unix and that for my particular use this is a valid benchmark.
| Language | Seconds |
| Asm (nasm) | 0.46 |
| C (llvm) | 0.84 |
| Obj-C (llvm) | 0.85 |
| C (gcc) | 0.87 |
| Sh | 1.11 |
| C++ (llvm) | 1.22 |
| Pascal (fp) | 1.48 |
| Awk | 1.83 |
| C++ (gcc) | 1.86 |
| Fortran (G95) | 2.15 |
| Brainfuck | 2.24 |
| Perl | 3.01 |
| Bash | 3.13 |
| Cobol (open) | 3.35 |
| Obfuscated Perl | 3.68 |
| Ruby | 5.35 |
| Tcl | 5.53 |
| Python | 16.33 |
| Php | 103.97 |
| Java | 121.88 |
| Groovy | 1318 |
Doing another benchmark where I basically let the hello world program contain a 1000000 long for-loop written in the program itself and then running this program 10 times I got different results:
GCC: timethis 10: 1 wallclock secs ( 0.00 usr 0.00 sys + 0.69 cusr 0.39 csys = 1.08 CPU) @ 9.26/s (n=10)
LLVM: timethis 10: 1 wallclock secs ( 0.00 usr 0.00 sys + 0.68 cusr 0.42 csys = 1.10 CPU) @ 9.09/s (n=10)
Perl: timethis 10: 2 wallclock secs ( 0.00 usr 0.00 sys + 1.73 cusr 0.44 csys = 2.17 CPU) @ 4.61/s (n=10)
Python: timethis 10: 8 wallclock secs ( 0.00 usr 0.00 sys + 6.41 cusr 0.68 csys = 7.09 CPU) @ 1.41/s (n=10)
Php: timethis 10: 40 wallclock secs ( 0.00 usr 0.00 sys + 7.20 cusr 28.15 csys = 35.35 CPU) @ 0.28/s (n=10)
Java: timethis 10: 111 wallclock secs ( 0.00 usr 0.01 sys + 36.21 cusr 61.36 csys = 97.58 CPU) @ 0.10/s (n=10)
Bash: timethis 10: 321 wallclock secs ( 0.00 usr 0.01 sys + 248.54 cusr 49.48 csys = 298.03 CPU) @ 0.03/s (n=10)
This speaks to the sluggishness of the different interpreters and virtual machines and/or the size of the executable. But it also underlines the importance of choosing which programming language you use wisely depending on the case you want to solve. Sure this is a moot point in most cases, but imaging taking development time into account. Writing something in PHP can be OK to solve a problem quickly, but seeing that writing the same code in Perl can be as easy or even easier and seeing the performance boost that script would have makes you wonder why PHP is even out there.
The most surprising result is the Bash. Running a simple bash-script 1000 times from the console is pretty snappy in terms of other scripting languages, but having bash loop a million times and running that is slower than even Java. That is a real surprise. The relative slowness of Python is also interesting, given that Python’s popularity is growing where Perl looses supporters. But equally as surprising is the speed at which Perl does this simple operation. Writing stuff in Perl is relatively straight forward (compared to C) but that does not seem to be a problem when doing menial tasks like this.
| Language | Seconds |
| Asm (nasm) | 0.46 |
| C (llvm) | 0.84 |
| Obj-C (llvm) | 0.85 |
| C (gcc) | 0.87 |
| Sh | 1.11 |
| C++ (llvm) | 1.22 |
| Pascal (fp) | 1.48 |
| Awk | 1.83 |
| C++ (gcc) | 1.86 |
| Fortran (G95) | 2.15 |
| Brainfuck | 2.24 |
| Perl | 3.01 |
| Bash | 3.13 |
| Cobol (open) | 3.35 |
| Obfuscated Perl | 3.68 |
| Ruby | 5.35 |
| Tcl | 5.53 |
| Python | 16.33 |
| Php | 103.97 |
| Java | 121.88 |
| Groovy | 1318 |
I need an algorithm that identifies all possible combinations of a set of numbers that sum to some other number.
For example, given the set {2,3,4,7}, I need to know all possible subsets that sum to x. If x == 12, the answer is {2,3,7}; if x ==7 the answer is {{3,4},{7}} (ie, two possible answers); and if x==8 there is no answer. Note that, as these example imply, numbers in the set cannot be reused.
This question was asked on this site a couple years ago but the answer is in C# and I need to do it in Perl and don't know enough to translate the answer.
I know that this problem is hard (see other post for discussion), but I just need a brute-force solution because I am dealing with fairly small sets.
Hi,
A few days ago I asked about passing a data structure from java to perl and vice versa, and one of the recos was JSON. I played with it (mainly using Gson for java) and it seems quite nice. The only problem is I have references inside my data structure (to other objects inside the same data structure). Currently, each such reference is "translated" fully so actually each object is duplicated many times, and you can't tell all those references pointed to the same object.
Is there someway to pass info from java to per and vice versa, preferably in a human readable format, that also keeps the data about references instead duplicating values?
Thamks, Dave



I am using the below code to send an email
#!/usr/bin/perl
sub BEGIN {
unshift (@INC,'/opt/dev/common/mds/perlLib');
}
use Mail::Sender;
$sender = new Mail::Sender
{smtp => 'xxx.xxx.x.xx', from => 'abc@xyz.xom'};
$sender->MailFile({to => 'abc@xyz.xom',
subject => 'Here is the file',
msg => "I'm sending you the list you wanted."});
$sender->Close;
But, it is not sending the mail at all. What is wrong in my code?
I have the following snippet calling a perl script which writes to STDERR and STDOUT. I've been following the recomended procedures such as auto flushing the STDOUT and STDERR in the perl script and using streamgobbler threads. I've noticed this to help my issue in to a degree but at times where the perl script generates large volumes of output it will still fill up its pipes and hang. The only thing that seems to stop this adding the following to my perl script however obviously I would like the output so this is not an option.
update >>
Another interesting occurence is when I cat the /proc/pid/fd/pipe# in linux it causes the pipe to be read to be accessed. This seems to dump the content of the pipe meaning my perl process can again write to it and thus complete. Must be therefore my java process is not reading the process output stream properly.
PERL :
close STDOUT
close STDERR
My java looks like the following
parserProcess = run.exec(config.getCMDArray(),env);
StreamGobbler errorGobbler = new StreamGobbler(parserProcess.getErrorStream(), "ERROR");
// any output?
StreamGobbler outputGobbler = new StreamGobbler(parserProcess.getInputStream(), "OUTPUT");
// kick them off
errorGobbler.start();
outputGobbler.start();
whereby StreamGobbler is ->
class StreamGobbler extends Thread
{
InputStream is;
String type;
StreamGobbler(InputStream is, String type)
{
this.is = is;
this.type = type;
}
public void run()
{
try
{
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line=null;
while ( (line = br.readLine()) != null)
System.out.println(type + ">" + line);
} catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
String line="";
status = parserProcess.waitFor();
Thanks in advance
Hi, I want to excecute a tail command in Unix for indefinite time and capture its output in a Perl script, process it and store certain data into a database. But it should be live, meaning old data – once stored in the database – shouldn't be reprocessed. It should only capture, and process only the most recent output.
Can someone please tell me how can this be done? Thanks in anticipation.
I'm trying to add some functionality to our code base by using tied scalars.
We have a function which is specified to return scalars. I thought I could add some features to the system by tie-ing these scalars before returning them, but it looks like the FETCH method is called just before the return, which results in an untied scalar being returned.
Is there any way around this?
I really want to keep the subroutine's interface (returning scalars) intact if it's at all possible.
use strict;
use warnings;
main();
sub GetThing{
my $thing;
tie $thing, 'mything', @_;
return $thing;
}
sub main {
my %m;
$m{pre} = GetThing('Fred');
print "1\n";
print $m{pre};
print "2\n";
print $m{pre};
print "3\n";
}
package mything;
require Tie::Scalar;
my @ISA = qw(Tie::StdScalar);
sub TIESCALAR {
my $class = shift;
bless {
name => shift || 'noname',
}, $class;
}
sub FETCH {
my $self = shift;
print "ACCESS ALERT!\n";
return " NAME: '$self->{name}'\n";
}
Desired output:
1
ACCESS ALERT!
NAME: 'Fred'
2
ACCESS ALERT!
NAME: 'Fred'
3
I can get the desired output by returning a reference, and dereferencing on each access, but that ruins our established interface, and makes it more confusing for our users.
--Buck
I'm trying to change strings like this:
<a href='../Example/case23.html'><img src='Blablabla.jpg'
To this:
<a href='../Example/case23.html'><img src='<?php imgname('case23'); ?>'
And I've got this monster of a regular expression:
find . -type f | xargs perl -pi -e \
's/<a href=\'(.\.\.\/Example\/)(case\d\d)(.\.html\'><img src=\')*\'/\1\2\3<\?php imgname\(\'\2\'); \?>\'/'
But it isn't working. In fact, I think it's a problem with Bash, which could probably be pointed out rather quickly.
r: line 4: syntax error near unexpected token `('
r: line 4: ` 's/<a href=\'(.\.\.\/Example\/)(case\d\d)(.\.html\'><img src=\')*\'/\1\2\3<\?php imgname\(\'\2\'); \?>\'/''
But if you want to help me with the regular expression that'd be cool, too!
Hi all,
when I run the following script.pl script with no arguments:
./script.pl
I do not get the message No arg. Why? How to identify if $param is a null value or empty value, same as [ -z from ksh?
#!/usr/bin/perl
my $param = $ARGV[0];
if ($param = "") {
print No arg;
} else {
print arg: $param;
}