Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation

Creating array name by susbtituting string

by Anonymous Monk
on Sep 12, 2017 at 09:31 UTC ( #1199181=perlquestion: print w/replies, xml ) Need Help??
Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I want to create different array name by passing the string , to identify each of the other arrays uniqueness. Here s the code

foreach my $R2 (@array) { push (@isis_adjacencies$R2, $R2); }

I am trying to create @isis_adjacencies$R2. I want the value of $R2 to be concanetaed with @isis_adjacencies to create a new array @isis_adjacencies$R2. Is it possible

Replies are listed 'Best First'.
Re: Creating array name by susbtituting string
by choroba (Bishop) on Sep 12, 2017 at 09:39 UTC
    Use a hash of arrays:
    my %isis_adjacencies; for my $R2 (@array) { push @{ $isis_adjacencies{$R2} }, $R2; }
    Do you really want to store the key as the value?

    See Why it's stupid to `use a variable as a variable name' for reasons not to do it the way you originally asked for.

    ($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,
Re: Creating array name by susbtituting string
by hippo (Abbot) on Sep 12, 2017 at 09:45 UTC
    Is it possible

    It is possible but it is also unwise. Use a HoA instead:

    #!/usr/bin/env perl use strict; use warnings; use Data::Dumper; my @array = qw/x y z/; my %HoA; foreach my $R2 (@array) { push @{$HoA{$R2}}, $R2 } print Dumper (\%HoA);

    See perldsc for how to work with deep structures.

Re: Creating array name by susbtituting string
by kcott (Chancellor) on Sep 12, 2017 at 10:00 UTC
    "Is it possible"

    While it's possible, it's almost certainly a really bad move.

    You really need to show the context of what you're hoping to achieve. If you do that, you can probably get a much better answer. Perhaps consider writing something like this:

    my %isis_adjacencies; for my $R2 (@array) { push @{$isis_adjacencies{$R2}}, $R2; }

    Here's the net effect of doing something like that:

    $ perl -MData::Dump -e 'my %x; my @y = qw{a b c}; push @{$x{$_}}, $_ f +or @y; dd \%x' { a => ["a"], b => ["b"], c => ["c"] }

    It seems unlikely that's what you want; however, in the absence of more information, I can but guess.

    See "perlref: Symbolic references" for more on what you're currently trying to do, why not to, and how to avoid doing it accidently by using the strict pragma (which you should be using anyway).

    — Ken

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1199181]
Approved by choroba
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (4)
As of 2017-10-21 03:05 GMT
Find Nodes?
    Voting Booth?
    My fridge is mostly full of:

    Results (269 votes). Check out past polls.