in reply to Re^4: Skipping parameters in sprintf %, elegantly
in thread Skipping parameters in sprintf %, elegantly
Thank you. The FAQ y'all referred me to says:
What is the difference between a list and an array?
An array has a changeable length. A list does not. An array is something you can push or pop, while a list is a set of values. Some people make the distinction that a list is a value while an array is a variable. Subroutines are passed and return lists, you put things into list context, you initialize arrays with lists, and you foreach() across a list. @ variables are arrays, anonymous arrays are arrays, arrays in scalar context behave like the number of elements in them, subroutines access their arguments through the array @_ , and push/pop/shift only work on arrays.
OK, so a list has most of the properties of an array, but is ephemeral -- appearing in expressions as terms or results. Hence 'list context', not 'array context'.
The FAQ also says:
As a side note, there's no such thing as a list in scalar context. When you sayyou're using the comma operator in scalar context, so it uses the scalar comma operator. There never was a list there at all! This causes the last value to be returned: 9.$scalar = (2, 5, 7, 9);
Which is vintage Perl :-) It may look like a list, it may even quack in a list-ish sort of a way, but it's not a list 'cos it's in scalar context. Hurrah !
With subroutines, context is a form of action over a distance -- quantum entanglement is, perhaps, a less tricky concept. Consider:
my $a = proc_a('fred') ; my $b = proc_b('bill') ; print "proc_a: $a\n" ; print "proc_b: $b\n" ; sub proc_a { my ($x) = @_ ; my @a = ($x.'_0', $x.'_1', $x.'_2', $x.'_3') ; return @a ; } ; sub proc_b { my ($x) = @_ ; return ($x.'_0', $x.'_1', $x.'_2', $x.'_3') ; } ;
gives:
proc_a: 4 proc_b: bill_3
So the occasional non-list-ness of the apparent list in proc_b is even less obvious. And the deceptive similarity between proc_a and proc_b is one of those optical illusions that remind us that evolution is a process, not a destination.
As a matter of Good Practice, where a subroutine expects to return a list (FX: checks definition... yes! subroutines return lists, not arrays) it should ensure that it has been invoked in the appropriate context, or responds in some well defined way in scalar context. Let me see, how does one do that ? Ah.... of course: wantarray (natch).
|
|---|