Log in

perl's Journal
[Most Recent Entries] [Calendar View] [Friends]

Below are the 20 most recent journal entries recorded in perl's LiveJournal:

[ << Previous 20 ]
Saturday, September 3rd, 2011
6:52 am
Script help
I need help with updating multiple files in a directory. I have a block of text (multiple lines) in multiple files that needs to be replaced with another block of text. I have the two blocks of text (one for the match, and the other for the replace) in two separate files. I just am clueless as to how to do do this. I can do simple regex search and replace on a single line of a single file but don't know how to apply the technique to multiple lines over multiple files. I am just not that strong in Perl.

Any suggestions?
Wednesday, July 13th, 2011
4:16 pm
Pulling unique combos from a multiset
What's the fastest way to iterate over an ordered list and pull out only unique combos? The particular application here is unique seven-letter racks drawn from a fresh bag of Scrabble tiles. In other words, calling a blank @ for ease of ASCII ordering, my first draw is @@AAAAA, and there are 2C2 * 9C5 ways to draw it. The next one is @@AAAAB, and there are 2C2 * 9C4 * 2C1 ways to draw it. Then @@AAAAC, etc. all the way to @@AAAAZ, then down to three As like @@AAABB, @@AAABC, @@AAACC, etc., ending with VWWXYYZ (two ways). Given a hash such as:

(@ => 2,
A => 9,
B => 2,
C => 2,
D => 4,
E => 12,
X => 1,
Y => 2,
Z => 1)

what's the quickest way extract the unique combos? Once I have a unique combo, I can very quickly calculate the number of ways to pull it, but iterating over the list of unique combos is the hard part, at least for me.

Ideas? Thanks in advance.

Friday, January 21st, 2011
4:34 pm
Time::HiRes no longer works
I recently upgraded to ActiveState Perl on my Window XP SP3 box. It is my understanding that this version has Time::HiRes built in and thus there's no need to install it. If this is correct, why does this code snippet:

use Time::HiRes qw(time);
my $ts = time();
die "\|$ts\|\n";

only return the epoch time to the second, not the millisecond?

Per PPM, I am running Time::HiRes 1.9721 dated 2010-03-17

Any thoughts? Do I have to rebuild Perl from scratch? Thanks!
Thursday, May 20th, 2010
11:14 am
Perl Survey 2010 is live

Here's the announcement I saw:

The Perl Survey 2010 is now live. Its purpose is to better understand the demographics and opinions of the Perl community. You can complete the survey at http://survey.perlfoundation.org - it should take about 10 to 15 minutes. Once you've done that, please let your relevant friends and colleagues know about the survey so they can coplete it as well. My aim is to get a response of over 1000 individuals, and to run the survey (lightly adapted) every two or three years so we can see how the community changes over time. The official announcement of the survey is here: http://news.perlfoundation.org/2010/05/grant-update-the-perl-survey-1.html

Wednesday, October 7th, 2009
6:21 pm
simple html parsing
Is there a simple and straightforward way to parse HTML text (from a string) into a perl data tree, using only the modules provided with a standard perl distribution? HTML::Parser is the closest I've found, but it seems designed for entirely different purposes, and looks like it'd require some tricky gymnastics to make it simple take a string of HTML and give me back a data structure of all the contents. I've found HTML::Parser::Simple which seems to be exactly what I want, but it's a nonstandard module that I don't even see in the normal Linux repos, so having a script that depends on the presence of that module would be a major pain. (Sure, I can find and install the module on one host, but my context is to write something that could work on many hosts, that I don't necessarily admin myself)
Sunday, August 23rd, 2009
5:46 pm
Maybe a stupid HASH question but....
I've been self-learning perl from books and websites, and I am confused about the benefit of hashes....
An example often given is...

%HoH = (
flintstones => {
husband => "fred",
pal => "barney",
jetsons => {
husband => "george"
wife => "jane",
"his boy" => "elroy", # Key quotes needed.
simpsons => {
husband => "homer",
wife => "marge",
kid => "bart",
So, why is this better than just having a bunch of variables like: 

$flintstones_husband = "fred";
$flintstones_pal = "barney";
$simpsons_husband = "homer";
$simpsons_wife = "marge";
and so on...?
Tuesday, April 28th, 2009
2:34 pm
Being aware of subclasses

I just joined the community and I wonder if I could jump straight in with a query.

I am writing a program that, given a directory with some files in it, would do the same functions to that directory, but in different ways based on the contents of the directory. That is, my directory may contain one of a number of different tests and I need to run those tests using different programs.

What I would like to be able to do is say "my $test = SomeClass->new($dir);" and have $test be set to a SomeClass::Foo, SomeClass::Bar etc. More importantly, I'd like the code to work if I, at a later time, create SomeClass::Baz.

I envision there being a detect() method with each class that says whether the given directory is suitable for this type, though clearly that could be done in new() (return undef if it's not suitable).

So, to cut a long story short, the point of my question is this: can I make SomeClass aware of subclasses before they even exist?
Saturday, December 6th, 2008
6:13 pm
CPAN? Might as well call it CPAIN.
Ok, no. I love CPAN. But, for all the things it does effortlessly, I have never had SOAP::Lite install from CPAN. It’s somewhere in the dependancies (it’s not expat, I have that). I always end up having to download source for several of the dependent modules, which install fine, and doing the rest one level at a time till I’m at the SOAP::Lite install. Anyone know why that is? Why would a module install with no special instructions or configuration options from a make command, but not CPAN? The closest I can figure is maybe some dependency is not detected correctly even though it is compiling correctly. Or maybe there is some problem with the requirements trees? Nah. Maybe just the tests, though I’d think they would be the same for make installs as CPAN installs. Anyone have some greater insight about this? Does this happen to you too?
Friday, November 21st, 2008
10:45 pm
Good to be bad.
Ok, this isn't something I would do in code that anyone would ever have to support or modify. This was purely a temporary monitoring script for an ill concieved application that, for dubious reasons, had 30 duplicate directories where logs could be written, depending on the day/time/traffic/phase of the moon/etc.

my @logs = grep {-e $_} map { "/opt/foo/bar/$_/logs/date.log" } 1..30;

I got a map, a grep, and a range operator all on one line and it returns an array of all the log files in the appropriate spots that actually exist. After so long making everything painfully clear this feels decadent. Really, I don't think it's that bad, but I guarentee no one else on my team would understand it. I just had to share with a group that would.

Note: I follow most of the tenets of Damian Conway's "Perl Best Practices" in my professional scripting.

Current Mood: devious
Wednesday, September 10th, 2008
5:17 pm
Including global variables

I have inherited hundreds of scripts which have some stuff hardcoded (which now need changing - lol). Anyway, I'd like to make a simple require file to put some globals in. Many of the scripts have package statements in them and most have "use strict" set. So I need a very general and reasonably fool-proof way to handle this. Here's what I came up with and wanted to bounce this off someone before actually implementing it:

include file:

use strict;

	$main::__SAVEPACKAGE = __PACKAGE__;

package GLOBAL;

our $GLOBALVAR1 = "value1";
our $GLOBALVAR2 = "value2";

eval "package $main::__SAVEPACKAGE; ";



Then using:

require 'my-globals.pl';
Monday, August 25th, 2008
2:09 pm
Perl moderately broken on RHEL
Hi LJ Perlers, long time lurker, first time poster.

This was a disturbing bit of news in my day. I had not noticed this due to usually compiling Perl manually, but I definitely have been suspecting something since I tried switching to the one RedHat ships. This guy just called it-- certain functions are really, really slow out of the box on RHEL-- and they just get slower the more you use them.


He provides a test which should exit very quickly on a "good" perl, and will take many seconds on a broken one.

# Perl compiled manually, runs in a snap:
sandbox# time perl perftest
real 0m0.108s
user 0m0.100s
sys 0m0.007s

# Redhat's stock Perl, took almost 19 seconds:
sandbox# time perl perftest
real 0m18.868s
user 0m18.726s
sys 0m0.072s

To tell if Perl on a system you use is affected, run the following code:

use overload q(<) => sub {};
my %h;
for (my $i=0; $i<50000; $i++) {
$h{$i} = bless [ ] => 'main';
print STDERR '.' if $i % 1000 == 0;

The only reliable "fix" at this point is to not use RedHat's Perl, and to compile it manually, including anything linked against it like mod_perl. Not fun.

Hope this comes in handy and/or helps spread the rage I'm feeling right now.
Monday, August 4th, 2008
9:55 pm
@INC hooks and tied filehandles

I'm currently working on an app where I've installed a CODE ref in @INC to hook the loading of certain modules. I can't seem to find any documentation on hooking @INC, so I'm just working from examples I've found. I've seen this work with normal filesystem handles:

use Symbol;
use lib sub {
	my $sym = gensym();
	open ($sym, '<', '/dev/null');
	return $sym;

The above will fail with the error that the included module did not return a true value, since of course /dev/null doesn't end with 1;.

What I'd like to be able to do is return a string containing source code. To do this, I attempted to use IO::String to create a tied handle that operates on a string in memory:

use IO::String;
use lib sub {
	warn $_[1];
	return IO::String->new("");

In this case, Perl just ignores my result and moves on to the next entry in @INC. Is there any way to make this work, or will hooking @INC only work on real system filehandles? (If it makes any difference, I'm running these on Perl 5.8.8.)

Partial Solution: After some searching about I found the docs for this nestled at the end of the require documentation. It seems that the hook sub can return a second argument which is another coderef that's called repeatedly to fetch lines of the source file. Rather bizarrely, it must set $_ to be the result and return 1, or return 0 to signal that there are no more lines. Even more bizarrely, this only works if the hook sub returns some kind of globref as its first return value. I just made a sub that returns the string on the first run and indicates the end on the second run, like this:

my $sym = Symbol::gensym();
my $done = 0;
return $sym, sub {
    if (! $done) {
        $_ = "die 'Blah'";
        return 1;
    else {
        return 0;

Quite why you need that random glob I'm not sure; the require documentation implies that it's optional. Perhaps someone else can shed some light.

Tuesday, July 15th, 2008
4:22 pm
Testing Poll
If you're a programmer (particularly Perl, but open to all), I'd be grateful if you could fill out my testing poll.
Friday, May 30th, 2008
7:18 pm
Text Game Questions

I'm creating a text game, basically a choose-your-own adventure, for my Intro to Unix class. I have some basic questions that I desperately need answered to even begin creating this game. I was told to try using Perl. What are your thoughts on this?
game questionsCollapse )

Is this the right place to post these questions?
Friday, April 25th, 2008
10:44 pm
YAPC in Chicago has something for everyone
From Perlbuzz:

The schedule for YAPC::NA just got published, and there's plenty of good stuff this year. If you haven't decided to make the trip out to Chicago June 16-18 yet, this should help.

Cool stuff that jumps out at me as I peruse the grid: JT Smith talking about the premade application stack that WebGUI uses, Schwern on testing data with The Sims, and Kevin Falcone on timezone handling.

For the beginners, Kent Cowgill's intro to testing is a great way to get introduced to the topic, and I'm sure that Leonard Miller talking about Perl::Tidy and Perl::Critic will help instill good coding practices.

New this year, on Wednesday there will be workshops. Stevan Little will host a 2-hour Moose tutorial, and Jim Keenan will help you get started building and working with Parrot and Rakudo Perl.

Do you have recommendations on must-see talks? Let your fellow Perlbuzz readers know in the comments below.

Sunday, April 6th, 2008
3:09 pm
Tuesday, March 18th, 2008
2:57 pm
Am I going insane?

This code snippet (line numbers are obviously not part of the code):

137:print "right before the weirdness, url=\|$url\|\n";
138:if ($url =~ /(jpg|gif|png)/i) {
[do something utterly irrelevant here]

sometimes, but not always, causes the following output:

right before the weirdness, url=|http://bp.specificclick.net?pixid=99002077|
Use of uninitialized value in pattern match (m//) at [scriptname].pl line 138.

We see that $url is non-null, and obviously (jpg|gif|png) is a constant, so how could either side of the pattern match be uninitialized? The script appears to work, but it keeps throwing this error. Oddly, this only started this week ago, and until it happened, I had made no recent changes, either to the code or to Perl.

I lack the necessary hubris to think that I've discovered a bug in Perl, rather than in my humble code, but the mind does boggle.

I am running Perl under Windows XP, SP2. There are 16 registered patches, none of which I installed manually, which I can provide if you think it's relevant.

Thanks in advance for your help!

Monday, March 17th, 2008
9:01 am
really basic question about installing ActiveState
so, I had PERL installed on my old computer at school. It seemed simple at the time. Then I would just so to my perl directory, type in "myprogram.pl" or whatever and my programs would run. I got a new computer so I installed perl. I copied my program of interest. I went to my new perl directory, but when I type in myprogram.pl it just opens the file in text editor. What am I doing wrong? I don't think I'm too dumb normally, but this just won't work at all.

Please help me so I can use all my old programs.
Wednesday, March 12th, 2008
9:09 pm
SOAP::Lite madness!
There's obviously something very fundamental I'm missing when if comes to object-oriented programming using SOAP::Lite.

My tale of SOAP woe...Collapse )
10:34 pm

I can't understand how sessions work in perl. I have read the manual on cpan but still can't get sessions to work.

When a user comes for the first time, he sees a login page. Enters his credentials in the form and the is redirected to the same login page where the script controls the username and password and if everything is ok, then the user is redirected to another page or in case of any problems the user sees the login form again.

On the login page I first create a session, then check whether the user is logged in or not and decide what to do next:
my $cgi = CGI->new();
my $session = new CGI::Session(undef, $cgi, {Directory=>"/tmp"});
if ($logged) { &redirect(); }
else {
    ... routines that check username and password ...
    ... if the username and pass are correct, then write some params, send cookie and redirect ...
    $session->param("logged", 1);
    my $cookie = $cgi->cookie(CGISESSID => $session->id);
    print $cgi->header( -cookie => $cookie);

This code seems to work, because I am being redirected to the proper page after submitting the login and password. On every other page I check whether the user is logged in or not and if not, then redirect him to the login page
my $cgi = CGI->new();
my $session = new CGI::Session(undef, $cgi, {Directory=>"/tmp"});
if ($logged != 1) { &redirect(); }
else { ... }

But every time I am being redirected to the login page. I looked in the /tmp and found 4 session files, 1 has "logged" parameter set and 3 sessions without "logged" being set. The first session is created when the user comes for the first time. The second one, as I understood, is created when the user submits his credentials. During this time the "logged" parameter is set. The third is created when I am redirected to another page (but why doesn't it pick already created session?) and the fourth when I am redirected back to the login page.
I also tried to create sessions like it is described in cpan:
my $sid = $cgi->cookie("CGISESSID") || undef;
my $session = new CGI::Session(undef, $sid, {Directory=>"/tmp"});

But has the same result. Tried to pass the session id with the URL. Didn't help.
Any ideas?
Thanks in advance

UPD: fixed. Passed the session id via URL and it worked. Guess, there is something wrong with my browser not receiving cookies
[ << Previous 20 ]
About LiveJournal.com