There are a couple of things we can do here to make it work.
First, let's tackle the @ascii
variable. The @
sigil indicates a positional variable, but you assigned a single string to it. This creates a 1-element array ['abc...']
, which will cause problems down the road. Depending on how general you need this to be, I'd recommend either creating the array directly:
my @ascii = <a b c d e f g h i j k l m n o p q r s t u v x y z>;
my @ascii = 'a' .. 'z';
my @ascii = 'abcdefghijklmnopqrstuvwxyz'.comb;
or going ahead and handling the any
part:
my $ascii-char = any <a b c d e f g h i j k l m n o p q r s t u v x y z>;
my $ascii-char = any 'a' .. 'z';
my $ascii-char = 'abcdefghijklmnopqrstuvwxyz'.comb.any;
Here I've used the $
sigil, because any
really specifies any single value, and so will function as such (which also makes our life easier). I'd personally use $ascii
, but I'm using a separate name to make later examples more distinguishable.
Now we can handle the map function. Based on the above two versions of ascii
, we can rewrite your map function to either of the following
{ push @tmp, $_.ord if $_ eq @ascii.any }
{ push @tmp, $_.ord if $_ eq $ascii-char }
Note that if you prefer to use ==
, you can go ahead and create the numeric values in the initial ascii
creation, and then use $_.ord
. As well, personally, I like to name the mapped variable, e.g.:
{ push @tmp, $^char.ord if $^char eq @ascii.any }
{ push @tmp, $^char.ord if $^char eq $ascii-char }
where $^foo
replaces $_
(if you use more than one, they map alphabetical order to @_[0]
, @_[1]
, etc).
But let's get to the more interesting question here. How can we do all of this without needing to predeclare @tmp
? Obviously, that just requires creating the array in the map loop. You might think that might be tricky for when we don't have an ASCII value, but the fact that an if
statement returns Empty
(or ()
) if it's not run makes life really easy:
my @tmp = map { $^char.ord if $^char eq $ascii-char }, "wall".comb;
my @tmp = map { $^char.ord if $^char eq @ascii.any }, "wall".comb;
If we used "wáll", the list collected by map
would be 119, Empty, 108, 108
, which is automagically returned as 119, 108, 108
. Consequently, @tmp
is set to just 119, 108, 108
.