Although I don't understand some bits, so if you could be so kind and explain them you'd be helping me fill one more page in my Perl notebook!Sure. Feel free to ask any questions.
$format just makes a format string for sprintf. It seems you're not familiar with that function. It is modeled after the famous printf function in the C programming language. I recommend you to just search the internet for something like "printf tutorial". There must be lots of those, and it's a very useful function in general.my $length = $total_length - length($prefix); my $format = "${prefix}%0${length}d";
The goal of the line my $format = "${prefix}%0${length}d"; is to produce a string like "AB%04d", which is a format string for sprintf.
Why "${prefix}" and not "{$prefix}"?${length} is actually a more useful example here. You know that you can interpolate variables in strings like so:"$variable". Suppose that I used $length instead of ${length}: "${prefix}%0$lengthd". Then Perl would've tried to find variable $lengthd (notice the d at the end), and there's no such variable. You can use curly braces to disambiguate: "${length}d". Now it's clear (to Perl) that $ goes with length, while d is just a character and is not a part of the variable's name.
And why ${prefix} instead of just $prefix? Just for symmetry with ${length}.
Another way to write it:my $format = $prefix . '%0' . $length . 'd';
Actually in general what confused me is that I thought Perl reads the script line by line from top to bottom. Now in this example we first use make_path and then set the subroutine. Shouldn't the subroutine be on top of everything else?Actually, no. Variables work like that, but not subroutines. I always put all subroutines at the bottom. That's different from some other programming languages and UNIX shells - in those, functions must also be put on top before you can actually use them - but not in Perl.
return map sprintf( $format, $_ ), $from .. $to;This is a pretty dense line. map is another famous function, from functional programming languages. You should read it right-to-left (like in Arabic):
That creates an anonymous list of numbers, starting with $from and ending with $to. For example, if $from is 1 and $to is 5, it will create (1, 2, 3, 4, 5). It's anonymous because it doesn't have a name and exists only temporarily in Perl's virtual machine.$from .. $to
map acts like a loop. It loops over anonymous list and invokes sprintf for each element of that list. map puts the result into another anonymous list. Like so:map sprintf( $format, $_ ), ANONYMOUS_LIST
and then return returns ANOTHER_ANONYMOUS_LIST from the make_seq function.for (ANONYMOUS_LIST) { STRING = sprint( $format, $_ ); put STRING into ANOTHER_ANONYMOUS_LIST; }
In reply to Re^3: make_path for creating directory tree
by Anonymous Monk
in thread make_path for creating directory tree
by fasoli
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |