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

Hello Shavenheaded-Ones,

Instead of doing something like

my @fields = split(/;/); my $obj = SomeClass->new(this => "$fields[0]", that => "$fields[1]", the_other => "$fields[2]", );

I would like to do something like:

my @fields = qw/this, that, the_other/; my %argsHash = ???; my $obj = SomeClass->new(%argshash);

Now that the various copies of the Perl CD Bookshelf on the Internet seem to have be knobbled, I couln't find out how to initialise the hash properly.

Can anymonk help?

Thanks,

loris

Replies are listed 'Best First'.
Re: Hash initialisation
by Happy-the-monk (Canon) on Nov 19, 2004 at 10:23 UTC

    How about this hash slice?

    @args_hash{ @fields } = split(/;/) ;

    use strict; to make perl tell you when you get some variable capitalisation/spelling wrong.
    Also test if split is actually doing the right thing there =)

    Cheers, Sören

Re: Hash initialisation
by davorg (Chancellor) on Nov 19, 2004 at 10:34 UTC
    Now that the various copies of the Perl CD Bookshelf on the Internet seem to have be knobbled

    Not all of them. There's still a copy on Safari.

    --
    <http://www.dave.org.uk>

    "The first rule of Perl club is you do not talk about Perl club."
    -- Chip Salzenberg

Re: Hash initialisation
by gothic_mallard (Pilgrim) on Nov 19, 2004 at 10:26 UTC

    If you can't find the CD bookshelf online (which it shouldn't be!) then check out http://www.perldoc.com for all the Perl documentation.

    If you're on *nix then you can use the man pages or if you're running ActiveState on win32 you should have the HTML docs with it.

    Failing that you could always buy the CD Bookshelf then you'd have it (legally) whenever you needed it...

    --- Jay

    All code is untested unless otherwise stated.
    All opinions expressed are my own and are intended as guidance, not gospel; please treat what I say as such and as Abigail said Think for yourself.
    If in doubt ask.

Re: Hash initialisation
by Eimi Metamorphoumai (Deacon) on Nov 19, 2004 at 14:49 UTC
    The hash slice is the best way to go, as Happy-the-monk said, but also be warned that in qw/this, that, the_other/ the commas will be included. You probably want to leave them out, as qw splits on whitespace without them.