Creating an array from an object function using a map

I have an array HTML::Elementderived from HTML::TreeBuilderand HTML::Element->find, and I need to assign their value to as_textsome other variables. I know that I can very easily do

my ($var1, $var2) = ($arr[0]->as_text, $arr[1]->as_text);

but I was hoping I could use it mapinstead to make the code more readable, since there are at least 8 elements in the array. I'm really new to Perl, so I'm not quite sure what to do.

Can someone point me in the right direction?

+5
source share
2 answers

If you are well versed perldoc -f map, this is pretty clear:

my @as_texts = map { $_->as_text } @arr;

It also works if you want to assign a list of scalars:

my($var1, $var2, $var3, ...) = map { $_->as_text } @arr;

, , .

+9

, @arr:

my($var1, $var2) = map { $_->as_text } @arr;

$_->as_text @arr. , :

my($var1, $var2) = map { $_->as_text } @arr[0 .. 1];

:

#!/usr/bin/perl

use strict;
use warnings;

my @arr = 'a' .. 'z';
my $count;
my ($x, $y) = map { $count++; ord } @arr;

print "$x\t$y\t$count\n";

$count = 0;
($x, $y) = map { $count++; uc } @arr[0 .. 1];

print "$x\t$y\t$count\n";

:

C:\Temp> jk
97      98      26
A       B       2

ord @arr, uc .

+1

All Articles