FromTheMotherland has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I'm working on a solution to handle aliases of strings (not variables) correctly. The idea is to read in a config file of the following format:

NAME1 alias1 alias2 alias3
NAME2 blah1 blah2
NAME3 m1 m2

After reading in the above, the following two should be equivalent:

alias1:blah1
alias2:blah1
...
...

I can explain in more detail what functionality I want if anyone has specific questions. This seemed like a very simple problem and I can cook up a hack in C++ but in perl i'm a newbie. Any help will be appreciated. thanks! Craig
  • Comment on Perl techniques for defeating this enemy?

Replies are listed 'Best First'.
Re: Perl techniques for defeating this enemy?
by kyle (Abbot) on May 05, 2007 at 04:58 UTC

    Reading the config file seems very straight forward.

    my %name_for; while (<>) { my ($name, @aliases) = split; $name_for{$_}=$name for ($name,@aliases); }

    After that, you can take a string of names/aliases and replace them with their real names like so:

    my $foo = 'alias1:blah1'; $foo =~ s/(\w+)/$name_for{$1}/g;

    That's assuming quite a few things about the format of $foo, however.

Re: Perl techniques for defeating this enemy?
by GrandFather (Saint) on May 05, 2007 at 08:08 UTC

    The key to your problem is an appreciation of the power of hashes in Perl. In C++ you may occasionally have used a hash map to allow using a non-integer value to lookup a value in an "associative array". In Perl hashes (hash maps/associative arrays) are fundamental to almost all significant projects. Perl hasn't the richness of types available in C++, but the few that are provided by Perl make up and more in their intrinsic power and richness of operations. Have a good read of perldata, perlref and perllol to get a feel for what can be done.


    DWIM is Perl's answer to Gödel