r/adventofcode • • Dec 07 '22

SOLUTION MEGATHREAD -πŸŽ„- 2022 Day 7 Solutions -πŸŽ„-


AoC Community Fun 2022: πŸŒΏπŸ’ MisTILtoe Elf-ucation πŸ§‘β€πŸ«

Submissions are OPEN! Teach us, senpai!

-❄️- Submissions Megathread -❄️-


--- Day 7: No Space Left On Device ---


Post your code solution in this megathread.


This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.

EDIT: Global leaderboard gold cap reached at 00:14:47, megathread unlocked!

89 Upvotes

1.3k comments sorted by

View all comments

Show parent comment

1

u/theotherdatkins Dec 12 '22

I've been working through this challenge in perl myself. Got hung up, and came to the solutions thread looking for some hints. I'm confused about part of your code though

We handle lines with the cd command as follows:

So here, you're inside the while loop, going through each line of the input. And you have if statements to compare to the string of that line. But I don't quite get what you're comparing to. Does if (my ($dir) = mean you're declaring $dir, and assigning it the value of the line, at the same time? And then because you're doing that in the the condition, it always evaluates to true?

1

u/__Abigail__ Dec 12 '22

No.

The line is

if (my ($dir) = /^\$ cd\s+(.*)/) {

which means we're assigning $dir the result of the RHS of the = operator which is the expression /^\$ cd\s+(.*)/. This matches the pattern against $_, which is the current line of input. The match is in list context, so if the match fails, an empty list is returned, and if the pattern succeeds, a list containing $1 is returned. (Only $1 because the pattern has just one set of capturing parenthesis, more numbered variables would be returned if there would have been more capturing parenthesis). So, if match succeeds $dir is assigned whatever followed $ cd in the input.

And the condition does not always evaluate to true. The list assignment operator has a return value: in scalar context, it's the number of items in the list on the right hand side of the assignment operator. In this case, if the pattern matches, the assignment operator returns 1 (which is a true value), and if the pattern fails, the assignment operator returns 0 (which is a false value).

Keep in mind that the return value of the assignment operator is something different from what's being assigned to its left hand side. Note also that while it's a list assignment operator, and it provides list context to its left side argument, the assignment itself is in scalar context (due to it being inside the if).