简体   繁体   中英

Shorthand to modify value in a array of hash refs

I have a array of hash refs. The date field in a hash is stored in epoch. I have to format it to human readable before returning the array. Following is my code:

for my $post (@sorted) {
        $post->{date} = format_time($post->{date});
        push @formatted, $post;
}

I have tried

my @formatted =  map {$_{date} = format_time($_{date})} @sorted;

All fields except {date} are dropped.

Is there any smarter method?

Thanks

$_->{date} = format_time($_->{date}) for @sorted.

然后@sorted中的日期将被转换。

There's nothing really wrong with the for loop you're currently using. The map can work too, but there are two problems:

  • The hashref in the array is stored in the scalar $_ . You are accessing the hash %_ .
  • The return value of the block is what will end up in the result array. In your case, that's the result of the assignment rather than the entire hashref.

Also, do note that the hashrefs in @sorted will be modified. The following map statement should work for you:

my @formatted = map { $_->{date} = format_time($_->{date}); $_ } @sorted;

If you really want:

sub format_time_in_place {
    my $time = $_[0];
    # do work
    $_[0] = $reformatted_time;
}

# elsewhere
format_time_in_place($_->{date}) for @sorted;

I helpfully renamed the function to reduce the odds of the maintenance programmer being tempted to become a homicidal axe murderer. There still may be an element of shock if said programmer was not aware that you can change passed in arguments with the correct manipulation of @_ .

This is equivalent to your code:

$_->{date} = format_time($_->{date}) for @sorted;
@formatted = @sorted;

I don't know why you want two identical arrays, but I don't see the point of combining those two unrelated operations. It'll just make your code less readable.

如果您希望或不介意不引用@sorted中相同的哈希,则可以:

my @formatted = map +{ %$_, 'date' => format_time($_->{date}) }, @sorted;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM