Skip to content

[doc] perldata hash slice example will blow up if used for more than depth 1 #17721

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
jidanni opened this issue Apr 16, 2020 · 5 comments
Open

Comments

@jidanni
Copy link
Member

jidanni commented Apr 16, 2020

perldata says

Since you can assign to a list of variables, you can also assign to an array or hash slice ...

@colors{'red','blue','green'} = (0xff0000, 0x0000ff, 0x00ff00);

The previous assignments are exactly equivalent to ...

($colors{'red'}, $colors{'blue'}, $colors{'green'}) = (0xff0000, 0x0000ff, 0x00ff00);

OK, but it needs to mention more than just one depth,

@{$colors{favorites}}{ 'red', 'blue', 'green' } #OK

Else users will extend the analogy presented, and assume

@colors{favorites}{ 'red', 'blue', 'green' } #syntax error

will work !

Also mention there is no way to use a consistent syntax for first vs.
more layers.

@khwilliamson
Copy link
Contributor

@jdanni, I'm trying to fix this, but I'm not good with slices. I don't understand what you mean

Also mention there is no way to use a consistent syntax for first vs.
more layers.

I'm happy to add your first example about needing to enclose @colors{favorites} with braces

@jidanni
Copy link
Member Author

jidanni commented May 4, 2025

Thanks but we will need a third person who is good with slices that go deeper than just one level to step in and interpret what I meant back in 2020 when I was slightly better with slices myself.

@guest20
Copy link

guest20 commented May 4, 2025

% export LC_ALL=en_AU 
% perl -MData::Dumper -E'
  my %colours;  
  @{ $colours{favourites} }{ 'red', 'blue', 'green' } = qw/r b g /; 
  say +Dumper+ \%colours 
' 
$VAR1 = {
    'favourites' => {
        'green' => 'g',
        'blue' => 'b',
        'red' => 'r'
    }
};

@Grinnz
Copy link
Contributor

Grinnz commented May 4, 2025

The request is that, when you are trying to slice an array or hash that is within another array or hash, you need to use the brace syntax (or postfix dereference syntax) to dereference $colors{favorites} as a list slice, because a naive @colors{favorites}{ 'red', 'blue', 'green' } as suggested will dereference the favorites key as a scalar and not a list slice (and then be a syntax error because of the @).

@Grinnz
Copy link
Contributor

Grinnz commented May 4, 2025

Or put another way, the hash you are trying to slice is $colors{favorites}, not %colors, so you cannot apply the @ sigil directly to %colors to do it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants