我的目标是将这个
my @array=("red", "blue", "green", ["purple", "orange"]);进入到这个
my @array = ( ["red"], ["blue"], ["green"], ["purple", "orange"]);当前测试代码:
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";
}
}发布于 2017-10-28 07:35:06
关于python的注释相当直接地映射到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 ];
}
}不过,使用Borodin的答案中的map会更自然。
发布于 2017-10-28 01:52:32
我想知道你为什么要这么做,但这是
@array = map { ref ? $_ : [ $_ ] } @array请不要调用数组@array;这就是@的作用。
你的评论太荒谬了
#if this was Python, it would be as simple as:
# if is not instance(item, array):
# # item wasn't a list
# item = [item]如果您熟悉Perl,那么就不需要问这个问题了。您必须知道,没有从Python到Perl的一对一转换。Python的表现力远不如Perl或C,但我无法想象您会要求简单地转换为C。
请克服你的偏执。
发布于 2017-10-28 01:56:28
如果将值推入新数组,只需计算$item是否为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;Dumper的输出:
$VAR1 = [
[
'red'
],
[
'blue'
],
[
'green'
],
[
'purple',
'orange'
]
];https://stackoverflow.com/questions/46980709
复制相似问题