I want to convert a code from perl to c++, and my problem is multi key map in perl! example:
perl:
$address{name}{familyName} = $someAddress;
and keys are not unique. I want similar data structure in c++ using map or ...!? also I want to search and obtain values with first key for example I want such %keys{name} in c++ .
Bejesus, top of the morning to you!
The beginning of another week in the 2010 Millionaire office and I realise that things have been fairly quiet on this front just from the number of people who’ve been banging on the door asking “what the devil has been going on?” “where are the updates?”.
When I say “banging” I mean, “calling” and unfortunately “the door” being my office phone.
Unfortunately it’s been ridiculously busy at work, and have spent the remainder of my time sat infront of the PC retouching wedding images. That’s not to say “unfortunately” about retouching, because I find it really relaxing and therapeutic, but just that I haven’t had much time to do anything else.
Also after more than 7 long years working at the same company I resigned a couple of weeks ago, which must have been one of the most difficult decisions I’ve had to make, maybe just because of the amount of weight I’d poured on it – but also as a testament to how much I think of the people I’ve had the opportunity of working with for so long.
I’ve got 4 weeks off from this Friday, the sun is coming out over central London and it’s difficult not to feel positive about life in general. Wedding enquiries have been going through the roof (7 in the last week) and have had 2 international bookings for this summer.
Since this week is my last week of work after so long I’ve found myself thinking “this is one of the last cups of tea I will make”, or “this is the last time I’ll walk thru the building atrium” and it dawned on me that there is only a fixed, finite number of times you’ll do anything in life. Obviously the same doesn’t apply to watching sunrise/sunsets and making cups of tea, but it’s made me think I’m going to try and stop taking these tiny events for granted, and in the same way you try and take in everything the last time you know you’ll see someone I’m finding myself thinking the same about my favourite office mug.
Have spent a fair bit of time coding, getting really interested in backtesting spread betting strategies from Malcolm Pryor’s book for spotting medium/long term UK stocks. What had been holding me back was just being able to find all the data that I wanted online, but glad to say it’s out there in the public domain – and I think am a couple of days away from having a nice automated perl script pumping out little graphs with entry & exit points, stop losses and returns.
Most of this week is going to be spent tying up loose ends, taking home 7 years worth of accumulated stuff from under my desk and maybe contributing a few C# interview questions to our list. The best interview questions I can think of though are:
Lionel Richie’s “3 Times a Lady” – the ultimate make up, or break up song .. discuss? (10 points)
Lionel Richie’s “Hello” – do you think that Lionel is describing a singleton pattern in C#? Or the song is more about loose coupling of objects? (10 points)
Lionel Richie’s “Say you, Say me” – describe what you think Lionel is telling us about C#’s model for event-handling and delegates? (10 points)
Photo today is from last year’s St Patrick’s day parade through New York.
This weekend I managed to package up Graphics::DZI. It is a naive implementation of the DeepZoom mechanism as used in Seadragon.
The API is not completely stable; first I will have to integrate the piece into my semantic map generation infrastructure.
I also need to better understand how to deal with very sparse maps.
Hello, is there a way to get with printf colored output?
#!/usr/bin/perl
use warnings;
use strict;
use Term::ANSIColor;
printf "%4.4s\n", colored( '0123456789', 'magenta' );
Output: (only newline)
I generally need to do a fair amount of text processing for my research, such as removing the last token from all lines, extracting the first 2 tokens from each line, splitting each line into tokens, etc.
What is the best way to perform this ? Should I learn Perl for this? Or should I learn some kind of shell commands? The main concern is speed. If I need to write long code for such stuff, it defeats the purpose.
Hello, I want to perform an http redirect, but the way i am currently doing it isn't working. When i try redirect it just prints the status code, and the location header
my $q = new CGI;
q->redirect(" http://www.google.com ");
I have a .ksh script that calls a perl pgm. The perl pgm creates some important data that the .ksh script needs to act on. Example:
.ksh pgm
#!/usr/bin/ksh
abc.pl > $logFile
# perl pgm creates variable $importantData See below.
# HOW DO I GET THE .KSH SCRIPT TO SEE $importantData ???
def.ksh $importantData # send important data to another .ksh script
exit
.
Perl pgm
$importantData = somefunction();
exit;
I need to create perl code which allows counting paragraphs in text files. I tried this and doesn't work:
open(READFILE, "<$filename")
or die "could not open file \"$filename\":$!";
$paragraphs = 0;
my($c);
while($c = getc(READFILE))
{
if($C ne"\n")
{
$paragraphs++;
}
}
close(READFILE);
print("Paragraphs: $paragraphs\n");
Is there a way to obtain the C++ equivalent of Perl's PREMATCH ($`) and POSTMATCH ($') from pcrecpp? I would be happy with a string, a char *, or pairs indices/startpos+length that point at this.
StringPiece seems like it might accomplish part of this, but I'm not certain how to get it.
in perl:
$_ = "Hello world";
if (/lo\s/) {
$pre = $`; #should be "Hel"
$post = $'; #should be "world"
}
in C++ I would have something like:
string mystr = "Hello world"; //do I need to map this in a StringPiece?
if (pcrecpp::RE("lo\s").PartialMatch(mystr)) { //should I use Consume or FindAndConsume?
//What should I do here to get pre+post matches???
}
pcre plainjane c seems to have the ability to return the vector with the matches including the "end" portion of the string, so I could theoretically extract such a pre/post variable, but that seems like a lot of work. I like the simplicty of the pcrecpp interface.
Suggestions? Thanks!
--Eric
Tom Christiansen's example code (à la perlthrtut) is a recursive, threaded implementation of finding and printing all prime numbers between 3 and 1000.
Below is a mildly adapted version of the script
#!/usr/bin/perl
# adapted from prime-pthread, courtesy of Tom Christiansen
use strict;
use warnings;
use threads;
use Thread::Queue;
sub check_prime {
my ($upstream,$cur_prime) = @_;
my $child;
my $downstream = Thread::Queue->new;
while (my $num = $upstream->dequeue) {
next unless ($num % $cur_prime);
if ($child) {
$downstream->enqueue($num);
} else {
$child = threads->create(\&check_prime, $downstream, $num);
if ($child) {
print "This is thread ",$child->tid,". Found prime: $num\n";
} else {
warn "Sorry. Ran out of threads.\n";
last;
}
}
}
if ($child) {
$downstream->enqueue(undef);
$child->join;
}
}
my $stream = Thread::Queue->new(3..shift,undef);
check_prime($stream,2);
When run on my machine (under ActiveState & Win32), the code was capable of spawning only 118 threads (last prime number found: 653) before terminating with a 'Sorry. Ran out of threads' warning.
In trying to figure out why I was limited to the number of threads I could create, I replaced the use threads; line with use threads (stack_size => 1);. The resultant code happily dealt with churning out 2000+ threads.
Can anyone explain this behavior?
I'm testing a socket to see if it's still open:
my $dummy = '';
my $ret = recv($sock, $dummy, 1, MSG_DONTWAIT | MSG_PEEK);
if (!defined $ret || (length($dummy) == 0
&& $! != EAGAIN && $! != EWOULDBLOCK )) {
logerr("Broken pipe? ".__LINE__." $!");
} else {
# socket still connected, reuse
logerr(__LINE__.": $!");
return $sock;
}
I'm passing this code a socket I know for certain is open and it's always going through the first branch and logging "Broken pipe? 149 Resource temporarily unavailable".
I don't understand how this is happening since "Resource temporarily unavailable" is supposed to correspond to EAGAIN as far as I know.
I'm sure there must be something simple I'm missing. And yes, I know this is not a full proof way to test and I account for that.
There is a perl script that needs to run as root but we must make sure the user who runs the script did not log-in originally as user 'foo' as it will be removed during the script.
So how can I find out if the user, who might have su-ed several times since she logged in has not impersonated 'foo' at any time in that chain?
I found an interesting perl script that was calling the following two shell scripts, but I think that would only work on Solaris.
my $shell_parent =
`ps -ef | grep -v grep | awk \'{print \$2\" \"\$3}\' | egrep \"^@_\" | awk \'{print \$2}'`;
my $parent_owner =
`ps -ef | grep -v grep | awk \'{print \$1\" \"\$2}\' | grep @_ | awk \'{print \$1}\'`;
This needs to work on both Linux and Solaris and I'd rather eliminate the repeated calls to he the shell and keep the whole thing in Perl.
I have a bunch of XML files that are about 1-2 megabytes in size. Actually, more than a bunch, there are millions. They're all well-formed and many are even validated against their schema (confirmed with libxml2).
All were created by the same app, so they're in a consistent format (though this could theoretically change in the future).
I want to check the values of one element in each file from within a Perl script. Speed is important (I'd like to take less than a second per file) and as noted I already know the files are well-formed.
I am sorely tempted to simply 'open' the files in Perl and scan through until I see the element I am looking for, grab the value (which is near the start of the file), and close the file.
On the other hand, I could use an XML parser (which might protect me from future changes to the XML formatting) but I suspect it will be slower than I'd like.
Can anyone recommend an appropriate approach and/or parser?
Thanks in advance.
Update
Here's the structure/complexity of the data I am trying to pull out:
<doc>
...
<someparentnode attrib="notme" attrib2="5">
<node>Not this one</node>
</someparentnode>
<someparentnode attrib="pickme" attrib2="5">
<node>This is the data I want</node>
</someparentnode>
<someparentnode attrib="notme"
attrib2="reallyreallylonglineslikethisonearewrapped">
<node>Not this one either and it may be
wrapped too.</node>
</someparentnode>
...
</doc>
The hierarchy goes a several levels deeper than that, but I think that covers off the sorts of things I am trying to do.
I'm using fork() on Perl in windows (activeperl) for a basic socket server, but apparently there are problems (it won't accept connections after a few times), is there any workaround?
while($client = $bind->accept()) {
$client->autoflush();
if(fork()){ $client->close(); }
else { $bind->close(); new_client($client); exit(); }
}
is the portion of the relevant code.
I'm trying to "hide" some of my perl program from the end user to make things easier on them. I'm doing what I can to keep them out of the command prompt. The program itself has a GUI designed in Perl/Tk, so they don't have to worry about the command prompt.
Could I write out a quick batch file that goes along the lines of:
START perl 'C:\[some path here]\myscript.pl'
with START to start a program, the perl interpretor as my program, and the path/name of my perl script as the parameter?
Would I have to specify where to find perl or would Windows just know because perl is in the computer's PATH variable?
Thanks for the help!
Can I use isa in Moose with a regex as a parameter ? If not possible can I achieve the same thing with someothing other than ->isa ?
ok, having the following types Animal::Giraffe , Animal::Carnivore::Crocodile , I want to do ->isa(/^Animal::/), can I do that ? if I can't, what can I use to reach the desired effect ?
Hello:
I'm tyring to remove lowercase sentence fragments from standard text files using regular expresions or a simple Perl oneliner.
These are commonly referred to as speech or attribution tags, for example - he said, she said, etc.
This example shows before and after using manual deletion:
"Ah, that's perfectly true!" exclaimed Alyosha.
"Oh, do leave off playing the fool! Some idiot comes in, and you put us to shame!" cried the girl by the window, suddenly turning to her father with a disdainful and contemptuous air.
"Wait a little, Varvara!" cried her father, speaking peremptorily but looking at them quite approvingly. "That's her character," he said, addressing Alyosha again.
"Where have you been?" he asked him.
"I think," he said, "I've forgotten something... my handkerchief, I think.... Well, even if I've not forgotten anything, let me stay a little."
He sat down. Father stood over him.
"You sit down, too," said he.
"Ah, that's perfectly true!"
"Oh, do leave off playing the fool! Some idiot comes in, and you put us to shame!"
"Wait a little, Varvara!" "That's her character,"
"Where have you been?"
"I think," "I've forgotten something... my handkerchief, I think.... Well, even if I've not forgotten anything, let me stay a little."
He sat down. Father stood over him.
"You sit down, too,"
I've changed straight quotes " to balanced and tried: ” (...)+[.]
Of course, this removes some fragments but deletes some text in balanced quotes and text starting with uppercase letters. [^A-Z] didn't work in the above expression.
I realize that it may be impossible to achieve 100% accuracy but any useful expression, perl, or python script would be deeply appreciated.
Cheers,
Aaron
I've got a bunch of questions about how people use exceptions in Perl. I've included some background notes on exceptions, skip this if you want, but please take a moment to read the questions and respond to them.
Thanks.
Perl has a very basic built-in exception system that provides a spring-board for more sophisticated usage.
For example die "I ate a bug.\n"; throws an exception with a string assigned to $@.
You can also throw an object, instead of a string: die BadBug->new('I ate a bug.');
You can even install a signal handler to catch the SIGDIE psuedo-signal. Here's a handler that rethrows exceptions as objects if they aren't already.
$SIG{__DIE__} = sub {
my $e = shift;
$e = ExceptionObject->new( $e ) unless blessed $e;
die $e;
}
This pattern is used in a number of CPAN modules. but perlvar says:
Due to an implementation glitch, the $SIG{DIE} hook is called even inside an eval(). Do not use this to rewrite a pending exception in $@ , or as a bizarre substitute for overriding CORE::GLOBAL::die() . This strange action at a distance may be fixed in a future release so that $SIG{DIE} is only called if your program is about to exit, as was the original intent. Any other use is deprecated.
So now I wonder if objectifying exceptions in sigdie is evil.
Do you use exception objects? If so, which one and why? If not, why not?
If you don't use exception objects, what would entice you to use them?
If you do use exception objects, what do you hate about them, and what could be better?
Is objectifying exceptions in the DIE handler a bad idea?
Where should I objectify my exceptions? In my eval{} wrapper? In a sigdie handler?
Are there any papers, articles or other resources on exceptions in general and in Perl that you find useful or enlightening.
Cross-posted at Perlmonks.
I'm using the date plugin for Template::Toolkit (Template::Plugin::Date), it works well with datetimes (yyyy-mm-dd hh:mm:ss) pulled straight out of MySQL, but it will not work with dates (yyyy-mm-dd).
What's the simplest way to get date.format to accept dates (without modifying the sql query)?
Thanks.
Recently I've been trying to get some files uploaded on to my server in my HTML::Mason application. All good no problems there apparently Mason a filehandle directly in the argument. The problem is that I cannot retrieve the filename from that filehandle in a elegant way. One method of resolving this issue is parsing the filename on the client before sending it to the server and placing the extracted value in a hidden field so that it gets sent upon submit. BUT that is very unsafe!
I have an environment variable set in Windows as TEST=abc£ which uses Windows-1252 code page. Now, when I run a Perl program test.pl this environment value comes properly.
When I call another Perl code - test2.pl from test1.pl either by system(..) or Win32::Process, the environment comes garbled.
Can someone provide information why this could be and way to resolve it?
The version of perl I am using is 5.8.
If my understanding is right, perl internally uses utf-8, so the initial process - test1.pl received it right from Windows-1252 → utf-8. When we call another process, should we convert back to Windows-1252 code page?
I have an array of strings: @array
I want to concatenate all strings beginning with array index $i to $j.
How can I do this?
I have been trying several regular expressions
$str =~ s/^0+(.)/$1/;
converts 0000 to 0 and 0001 to 1
$str =~ s/^0+./$1/;
converts 0000 to empty string, 000100 to 00, 0001100 to 100.
what difference is the parentheses making?
How do I initialize a 2d array in perl?
I am trying the following code:
0 use strict;
10 my @frame_events = (((1) x 10), ((1) x 10));
20 print "$frame_events[1][1]\n";
but it gives the following error:
Can't use string ("1") as an ARRAY ref while "strict refs" in use at ./dyn_pf.pl line 20.
This syntax only seems to initialize a 1d array as print "$frame_events[1]\n" works. Though perl doesn't give any error during the assignment.
A few command-line tricks for Perl: