For Programmers: Free Programming Magazines  


Home > Archive > PERL Miscellaneous > June 2005 > Slice returned hash or access to its elements without assigning to a variable









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author Slice returned hash or access to its elements without assigning to a variable
Andrew

2005-06-11, 3:57 pm

Hi,

Please help me in solving next problem(I search in FAQ bun have not
find an answer):
There is a sub foo which return hash:

sub foo{my %in=( key1=>value1
key2=>value2
key3=>value3);
}
I need to assess elements of returned hash without assigning to a
variable. Something like this:
print @&foo(){'key1','key2'};
print $&foo(){'key1'};

But this does not work: "Bareword found where operator expected"

Thanks,
Andrew

Glenn Jackman

2005-06-11, 3:57 pm

At 2005-06-11 12:35PM, Andrew <les_andrey@yahoo.com> wrote:
> Hi,
>
> Please help me in solving next problem(I search in FAQ bun have not
> find an answer):
> There is a sub foo which return hash:
>
> sub foo{my %in=( key1=>value1
> key2=>value2
> key3=>value3);
> }


Strictly speaking, this returns a 6-element list, not a hash.

> I need to assess elements of returned hash without assigning to a
> variable. Something like this:
> print @&foo(){'key1','key2'};
> print $&foo(){'key1'};
>
> But this does not work: "Bareword found where operator expected"


Coerce the returned list from foo into a hash ref, and dereference
accordingly:
sub foo { (a=>1,b=>2,c=>3) }
$b = +{foo()}->{b};
@arr = @{%{+{foo()}}}{'a','b'}

--
Glenn Jackman
NCF Symin
glennj@ncf.ca
Glenn Jackman

2005-06-11, 3:57 pm

At 2005-06-11 12:35PM, Andrew <les_andrey@yahoo.com> wrote:
> Hi,
>
> Please help me in solving next problem(I search in FAQ bun have not
> find an answer):
> There is a sub foo which return hash:
>
> sub foo{my %in=( key1=>value1
> key2=>value2
> key3=>value3);
> }


Strictly speaking, this would return a 6-element list, not a hash, if it
was proper Perl.
sub foo { (a=>1,b=>2,c=>3) }

> I need to assess elements of returned hash without assigning to a
> variable. Something like this:
> print @&foo(){'key1','key2'};
> print $&foo(){'key1'};
>
> But this does not work: "Bareword found where operator expected"


Coerce the returned list from foo into a hash ref, and dereference
accordingly:
$b = +{foo()}->{b};
@arr = @{%{+{foo()}}}{'a','b'}

--
Glenn Jackman
NCF Symin
glennj@ncf.ca
Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2009 codecomments.com