Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use Perl's map with an array slice?

I'm just trying to shorten a line of code that assigns HTML::Element->as_trimmed_text from an array of HTML::Elements to some variables - pretty standard stuff like:

my ($var1, var2) = ($columns[1]->as_trimmed_text, $columns[2]->as_trimmed_text);

..except that there's a few more columns so it continues on over a few more lines. I had the bright idea that I could use map instead but I'm not really having much luck. I've tried variations on

map { $_->as_trimmed_text } @columns[1, 3, 5, 7, 9]

but I keep getting Can't call method "as_trimmed_text" without a package or object reference.

Is it possible to do what I'm trying or should I just stick to what I currently have?

TIA

EDIT: column -> columns

like image 639
Sparkles Avatar asked May 21 '26 04:05

Sparkles


2 Answers

Found it:

Here's a bit of code that emulates what should happen:

use strict;
use warnings;

package Text;

sub new
{
   my $class = shift;
   my $text = shift;
   return bless { TEXT => $text }, $class;
}

sub as_trimmed_text
{
   my $self = shift;
   my $text = $self->{TEXT};
   $text =~ s/^\s*(.*?)\s*$/$1/;
   return $text;
}

package main;

my @texts = ( Text->new(' foo '), Text->new(' bar '), Text->new(' baz '));

my @trimmed = map { $_->as_trimmed_text() } @texts[1, 2];

print "Trimmed were: ", join(',', map { "'$_'" } @trimmed);

This works, and works fine; I get:

Trimmed were: 'bar','baz'

But if I replace the map with this line:

my @trimmed = map { $_->as_trimmed_text() } @texts[2, 3];

All of a sudden I get this output:

Can't call method "as_trimmed_text" on an undefined value

This is because '3' is outside the range of valid values in @texts, so it autovivifies a new entry, and makes it undef. Then, your map does

undef->as_trimmed_output()

which barfs. I'd check your array slice again, and make sure that you aren't grabbing values outside the actual indexes available, and barring that, verify that you are actually processing HTML::Element members with that map. A quick Data::Dumper::Dumper on the values in @columns will help immensely.

For example, if you then change your array to contain

my @texts = ( Text->new(' foo '), Text->new(' bar '), ' baz ');

and try to run it, I now get your error:

Can't call method "as_trimmed_text" without a package or object reference at map.pl

So, double check to make sure the contents of your array are actually all blessed instances of the class you're trying to call the method of.

like image 122
Robert P Avatar answered May 24 '26 14:05

Robert P


Your map looks right to me. Are you sure the second one should say @columns instead of @column? Do you have strict turned on to catch typos in variable names?

like image 42
friedo Avatar answered May 24 '26 14:05

friedo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!