1

My goal is to convert this

my @array=("red", "blue", "green", ["purple", "orange"]);

into this

my @array = ( ["red"], ["blue"], ["green"], ["purple", "orange"]);

Current test code:

my @array = ("red", "blue", "green", ["purple", "orange"] );

foreach $item ( @array ) {
   #if this was Python, it would be as simple as:
   #  if is not instance(item, array):
   #     # item wasn't a list
   #     item = [item]

   if(ref($item) ne 'ARRAY'){
      #It's an array reference...
      #you can read it with $item->[1]
      #or dereference it uisng @newarray = @{$item}
      #print "We've got an array!!\n";
      print $item, "\n";
      # keep a copy of our string
      $temp = $item;
      # re-use the variable but convert to an empty list
      @item = ();
      # add the temp-copy as first list item
      @item[0] = $temp;
      # print each list item (should be just one item)
      print "$_\n" for $item;
   }else{
      #not an array in any way...
       print "ALREADY an array!!\n";

   }
}

#  EXPECTED my @array=(["red"], ["blue"], ["green"], ["purple", "orange"]);
print @array , "\n";

foreach $item (@array){
    if(ref($item) ne 'ARRAY'){
    #
    #say for $item;
    print "didn't convert properly to array\n";
   }
}

4 Answers 4

2

The comment about python maps pretty directly to perl.

my @array = ("red", "blue", "green", ["purple", "orange"] );

foreach $item ( @array ) {
   #if this was Python, it would be as simple as:
   #  if is not instance(item, array):
   #     # item wasn't a list
   #     item = [item]
   if (ref $item ne 'ARRAY') {
       $item = [ $item ];
   }
}

though using map as in Borodin's answer would be more natural.

Sign up to request clarification or add additional context in comments.

Comments

1

I'm wondering why you want to do this, but it's

@array = map { ref ? $_ : [ $_ ] } @array

And please don't call arrays @array; that's what the @ is for.


Your comment is ridiculous

#if this was Python, it would be as simple as:
#  if is not instance(item, array):
#     # item wasn't a list
#     item = [item]

If you were familiar with Perl then you wouldn't need to ask the question. You must be aware that there is no one-to-one translation from Python to Perl. Python is much less expressive than either Perl or C, but I can't imagine you demanding a simple conversion to C.

Please get over your bigotry.

10 Comments

It's troubling that someone's tribalism was so intense.
obviously the poster is unfamiliar with Perl, otherwise such a simple question wouldn't have been asked. The mention of Python was obviously to establish some credibility and parity between a language in which they know how to get their stuff done.
@nmz787: "I was helping OP earlier on chat elsewhere" Then it is unreasonable of you to expect others to take a question on face value when you know that there is a lot more behind it. It is also unreasonable to take it personally when your advice results in a poorly-presented question.
@nmz787: I don't understand. It is your solution that doesn't behave in the same way as the OP's code. I wouldn't normally overwrite the original data, but I wrote it that way as that is what the OP asked for. You had to write a comment to explain how to change your solution so that the original array was modified. Either way I don't see that either your answer or mine deserves a negative vote. This whole exchange is about anger and hurt feelings rather than good programming.
I don't see any language bigotry or ridiculousness in "If this were Python"; that says there is a trivlal way to do what they want in Python, but doesn't say there isn't also such a way in Perl, just that they don't know it. You are reading into it commentary on Perl that isn't actually there.
|
0

If you push the values to a new array, you don't need to do more than evaluate whether or not $item is an arrayref:

#! perl

use strict;
use warnings;

use Data::Dumper;

my @array=("red", "blue", "green", ["purple", "orange"]);

my @new_array;
foreach my $item (@array) {

    if ( ref($item) eq  'ARRAY' ) {
        push @new_array, $item;
    }
    else {
        push @new_array, [$item];
    }
}

print Dumper \@new_array;

Output from Dumper:

$VAR1 = [
          [
            'red'
          ],
          [
            'blue'
          ],
          [
            'green'
          ],
          [
            'purple',
            'orange'
          ]
        ];

9 Comments

Why use for when you want map?
Because I matched my answer to his example. He's clearly coming from python and is new to perl. I've found it's much easier for people to adapt to a new language if you use code structures they're already familiar with.
can you answer with the in-line modification, rather than creating a new array?
That's fair, but the OP seemed to have written a solution using Perl and for. Doesn't it work? They didn't say either way, but I assumed it was working code that should have been as brief as their Python original. I can't run any code at present as I'm on my commute. Hopefully this will stop soon.
@Borodin: I can see how you could get that impression from the way the question is worded. I think my years doing customer support and access to an editor gave me an edge there. :) Your answer is definitely the one I would go with when writing production code.
|
0

After a long day of learning more Perl than I ever thought/wanted to learn... here's what I think is a workable solution:

#! perl

use strict;
use warnings;

use Data::Dumper;


my %the_dict = (duts => 
                    {dut_a => {UDF => 'hamnet'},
                     dut_b => {UDF => [ '1', '2', '3', ]},
                     dut_c => {UDF => [ 'Z' ], }});

print Dumper \%the_dict;

foreach my $dut (keys %{$the_dict{duts}}) {
    # convert the dut's UDF value to an array if it wasn't already
    if ( 'ARRAY' ne ref $the_dict{duts}->{$dut}{UDF} ) { 
        $the_dict{duts}->{$dut}{UDF} = [ $the_dict{duts}->{$dut}{UDF} ]; 
    }
    # now append a new value to the array
    push(@{$the_dict{duts}{$dut}{UDF}}, 'works');
}

print Dumper \%the_dict;

when run we see these print-outs:

$VAR1 = {
          'duts' => {
                      'dut_a' => {
                                   'UDF' => 'hamnet'
                                 },
                      'dut_c' => {
                                   'UDF' => [
                                              'Z'
                                            ]
                                 },
                      'dut_b' => {
                                   'UDF' => [
                                              '1',
                                              '2',
                                              '3'
                                            ]
                                 }
                    }
        };
$VAR1 = {
          'duts' => {
                      'dut_a' => {
                                   'UDF' => [
                                              'hamnet',
                                              'works'
                                            ]
                                 },
                      'dut_c' => {
                                   'UDF' => [
                                              'Z',
                                              'works'
                                            ]
                                 },
                      'dut_b' => {
                                   'UDF' => [
                                              '1',
                                              '2',
                                              '3',
                                              'works'
                                            ]
                                 }
                    }
        };

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.