I'm trying to port a library from Javascript to Perl, but having some issues detecting array arguments.
A stripped-down example (in Javascript) looks something like this:
const say = console.log;
function test(array, integer)
{
if(Array.isArray(array))
{
say("First argument is array");
}
else
{
say("First argument is not array");
array = [array];
}
for(let index = 0; index < array.length; ++index)
{
say(array[index]);
}
say("Second argument: ", integer);
say("");
}
var a = ["foo", "bar"];
var t = "baz";
var i = 1024;
say("Testing on array");
test(a, i);
say("Testing on string");
test(t, i);
Output:
Testing on array
First argument is array
foo
bar
Second argument: 1024
Testing on string
First argument is not array
baz
Second argument: 1024
And here's the Perl version:
use feature qw(say);
sub test
{
my ($text, $integer ) = @_;
my (@array) = @_;
if(ref(@array) == "ARRAY")
{
say("First argument is array");
}
else
{
say("First argument is not array");
@array = ($text);
}
for my $index (0 .. $#array)
{
say($array[$index]);
}
say("Second argument: ", $integer);
}
my @a = ("foo", "bar");
my $t = "baz";
my $i = 1024;
say("Testing on array");
test(@a, $i);
say("Testing on string");
test($t, $i);
Output:
Testing on array
First argument is array
foo
bar
1024
Second argument: bar
Testing on string
First argument is array
baz
1024
Second argument: 1024
I've also tried numerous other ways, such as prepending the backslash to the array name and so forth, but to no avail. I'm fairly certain that this must be possible in Perl. Or perhaps this is some sort of limitation of the language itself?