Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

need an array ref from grep

by jeanluca (Deacon)
on Jun 16, 2006 at 14:53 UTC ( [id://555800]=perlquestion: print w/replies, xml ) Need Help??

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

Dear Monks

Is there some way that I can convert the result from grep (which is an array) into an array reference. I tried (without succes) the following:
my %h = ( 'a1' => 1, '001' => 1, '993' => 1, 'd' => 1, 'i' => 1) ; my $arr_ref = \(grep ( /[[:alpha:]]/, (keys(%h)) )) ;
Somehow the \ in this case doesn't do what I need.
Any suggestions

Thnkx
LuCa

Replies are listed 'Best First'.
Re: need an array ref from grep
by davido (Cardinal) on Jun 16, 2006 at 15:03 UTC

    Like this, perhaps:

    my $arr_ref = [ grep( /[[:alpha:]]/, keys %h ) ];

    The [...] brackets are used as an anonymous array constructor.


    Dave

Re: need an array ref from grep
by jeffa (Bishop) on Jun 16, 2006 at 15:03 UTC
Re: need an array ref from grep
by jhourcle (Prior) on Jun 16, 2006 at 16:54 UTC
    Somehow the \ in this case doesn't do what I need.

    Correct. The following:

        \( ... )

    takes a reference of every item in the list, without flattening it first.

    See the following as an example:

    This is also a useful trick for getting a reference to a scalar when your editor's syntax coloring (eg, BBEdit) thinks you're escaping a quote:

    my $var = \('string');
Re: need an array ref from grep
by monkey_boy (Priest) on Jun 16, 2006 at 15:04 UTC
    Small change needed, use the anonymous array syntax:
    my %h = ( 'a1' => 1, '001' => 1, '993' => 1, 'd' => 1, 'i' => 1) ; my $arr_ref = [(grep ( /[[:alpha:]]/, (keys(%h)) ))] ;



    This is not a Signature...
Re: need an array ref from grep
by orderamidchaos (Initiate) on May 29, 2013 at 00:41 UTC

    I know this is super old at this point, but for anyone else who references such things in their searches, here's another (IMHO cleaner) way to write greps...

    my $arr_ref = [ grep {/[[:alpha:]]/} keys(%h) ];

    You can also assign the result to a dereferenced variable:

    my $arr_ref; @$arr_ref = grep {/[[:alpha:]]/} keys(%h);
A reply falls below the community's threshold of quality. You may see it by logging in.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://555800]
Approved by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (5)
As of 2024-03-28 15:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found