2

I'm new in Perl and appreciate much if someone can help me on this.

foreach $line(@resultans){
    my @newresultans = split "_",$line;

    ## i will have lots more of $newresultans and @ans
    push(@ans1, $newresultans[2]);
    push(@ans2, $newresultans[3]);
    ......
    ......

 }

My intention is to split something like this, and push them into many arrays.

12, 2, and so on in the following rows pushed into an array(@ans1). Same goes to 6, 7 (@ans2) and there are much more numbers after that,separated by _. which is to form @ans3, @ans4

2_abc_12_6_.......
2_def_2_7_......
.................

Can I try something like this? but it doesn't seem to work. I really appreciate a lot if someone can help me. Thanks!!

$ANS_name ="ANS_$colnm";

foreach $line(@resultans){
    my @newresultans = split "_",$line;

    for($colnm=0;$colnm <=$column[0] ; $colnm++){
        push(@$ANS_name, $newresultans[2]);
    }
}

2 Answers 2

3

It seems to me like what you are saying is that you have a variable amount of columns in each split, and you want a dynamic - rather than hard coded - way to store them. I think what you are looking for is an array or arrays:

my @all;
for my $line (@res) {
    my @new = split /_/, $line;   # split takes a regex, not a string (normally)
    for my $index (0 .. $#new) {
        push @{ $all[$index] }, $new[$index];
    }
}

Your idea about patching together variable names is quite bad, and you should avoid that. If for nothing else that it is exactly what a hash does, but you don't have to break any rules to use a hash. We could have used a hash here, but there was no point since your data was serial, and you had no fixed names. For example:

my %hash;
...
for my $index( 0 .. $#res ) {
    $ANS_name ="ANS_$index";
    push @{ $hash{$ANS_name} }, $new[$index];
}
Sign up to request clarification or add additional context in comments.

Comments

1

What you're asking is possible, but frowned upon. It is much better to use an array of arrays:

my @column;
for my $line (@resultans) {
  my (undef, undef, @parts) = split /_/, $line;  # discard first 2 elements
  push @{ $column[$_] }, $parts[$_] for 0 .. $#parts;
}

Then @column would be:

(
  [12, 2],
  [6, 7],
)

We can access the entries for the first column like @{ $column[0] }.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.