Thanks Gil, that helped me to understand the context of the code presented in the book.
Le 18 sept. 2016 18:02, "Gil Magno" <gilma...@gilmagno.com> a écrit : > Hi Khalil > > 'say' creates list context. So if 'say' receives the list ('one', 'cd', > 'qw') it will print 'abcdqw'. > > 'reverse' creates list context. So if 'reverse' receives the list ('ab', > 'cd', 'qw') it will return a list with the same elements, but with its > order inverted ('qw', 'bc', 'ab'). > > The catch is that if 'reverse' is forced to be evaluated in scalar > context, then it will 1) concatenate the elements of the list we give to > it, 2) treat the concatenated result as a string and 3) invert the string. > > To force one expression to be evaluated in scalar context, you should > give that expression as an argument to the 'scalar' function. So in > reverse(1, 2, 3); 'reverse' is evaluated in *list* context and the list > returned is (3, 2, 1) , but in scalar(reverse(1, 2, 3)) 'reverse' is > evaluated in *scalar* context, so 1, 2, 3 are concatenated to the string > '123', then the string is inverted to '321' and then it is returned by > 'reverse'. > > Now we come to 'say'. 'say' still creates list context, but the list it > receives from scalar(reverse(1, 2, 3)) is a list of just one element: > the element '321'. So 'say' prints '321'. > > If you didn't understand something or if it is still confuse, don't > hesitate to ask further questions. :) > > On 18/09/16 12:43, khalil zakaria Zemmoura wrote: > > Hi everyone, > > > > I'm reading the modern perl book and I have some questions to address > about > > scalar and list context. > > > > Here is the code that I want to understand. > > > > while (<>) { chomp; say scalar reverse; } > > > > Where I'm struggling is : say scalar reverse; > > > > The book says that 'say' impose list context to Its operands. 'reverse' > > impose list context on to its operands and treat them as a list in list > > context and a concatenated string in scalar context. > > > > The questions are: > > > > Is 'say' that is imposing list context in 'reverse' or 'reverse' it self > > treats it's operands in list context or it's both? > > > > The most confusing part: > > There is 'scalar' before 'reverse', so 'reverse' is evaluated in scalar > > context! > > So how can reverse executing in both contexts (list and scalar context)? > > > > I'm sure I missed something. > > > > It will be great if I have more explanation. > > > > Thank you. > > Regards, Zakaria > > > > -- > To unsubscribe, e-mail: beginners-unsubscr...@perl.org > For additional commands, e-mail: beginners-h...@perl.org > http://learn.perl.org/ > > >