I'm playing with lists in #perl. Below is a small example of using first_index from https://metacpan.org/pod/List::MoreUtils to implement a function that replaces the first occurrence of a value with a new value.
@trurl You're right. That should've been a $ and not a @ - code reviews rocks!. I must be assigning the value to a slice with only one element. You can assign to a slice like this: @list[1,4]=(2,3) - never done that, don't know if it's a good idea or if that has always been possible.
@slu thanks for sharing some code! Haven't had a reason to think about Perl for a very long time now, and it's nice to have a casual reason to. And there are now real argument signatures for subroutines! Been some progressive changes since 10 years ago.
@slu for small lists I think the overhead of using that module just to find and replace the first element seems like overkill. In fact, wrapping grep in a function that just feeds it values seems artificially verbose. What attracted me to Perl was the ability to avoid writing lots of unnecessary code to get things done.
@slu Note: on L13 you'll want:
$list[$index] = $replacement;
@list[$index] does an array slice, which, while it produces the correct result here, is probably not what you want and is more expensive than a direct array assignment.
Also note: if I were writing this, I'd probably just skip the module and directly iterate over the list like so:
for my $item (@list) {
if ( $item == $value ) {
$item = $replacement;
last;
}
}
return @list;
@slu back when I was writing Perl for a living, I would have written `$list[$index] = $replacement`. Am I misunderstanding, or has something changed?
I know that Perl 6 (now Raku) decided to adopt a different semantics for sigils. (Lists are always @list, even when indexing into them.) I have found a couple of references to Perl sigil behavior changing when slicing into hashes or lists, but I don't see anything suggesting that a indexing into a list with a scalar should use @ instead of $.