Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Easy Reference for Contexts

by cat_baby (Novice)
on Apr 14, 2011 at 06:53 UTC ( [id://899364]=perlquestion: print w/replies, xml ) Need Help??

cat_baby has asked for the wisdom of the Perl Monks concerning the following question:

Hello, wise Perl friends.

There ought to be a repository of common expressions and how they behave in each context / what their default context is. I know there are tons of vanilla examples found in tutorials everywhere (such as assigning an array to a scalar) but some slightly more sophisticated operations still trip me up.

For example:

m/.../ returns true or false in scalar context m/.../g give you a list of matches in list context m/(...)/ can populate an array with whatever gets captured... (??)
while( ) i.e. inside parenthesis is evaluated in scalar context? foreach( ) i.e. inside parenthesis is evaluated in list context?
<STDIN> returns the next line of input in list context

In fact, I could be wrong on a lot of these but that's not my point. Is there a handy reference-like guide available anywhere that tells you how these expressions behave?

Replies are listed 'Best First'.
Re: Easy Reference for Contexts
by davido (Cardinal) on Apr 14, 2011 at 07:23 UTC

    Your questions on regular expressions, and what they do in various contexts, with and without capturing parenthesis would probably be answered in perlre, perlrequick, and perlretut. There is additional reading proscribed at the bottom of each of those docs.

    perlsyn discusses while(){}, but think of it this way: while evaluates a condition. In other words, while some condition exists, the loop proceeds. It's more akin to an "if()" statement except that the test repeats again and again until it fails. The test is a Boolean test; true or false. It doesn't make sense to discuss list context in terms of a Boolean evaluation.

    foreach(), on the other hand, is an iterating loop construct. The Perl-style foreach iterates over a list of elements until it finishes with the last one. For each element in the list, there's one iteration, or one execution of the code within the blocks. In such a case it should be fairly obvious that the context is list context. On the other hand, the C style foreach loop is a bit of a special case. It provides a mechanism for the creation of a counter variable, does a conditional test (which is Boolean), and then provides a mechanism for incrementing the counter. But in this special case, it doesn't make sense to be talking about list context. In fact, perlop (in the section talking about IO operators) alludes to the fact that a for(;;) loop is sort of a disguise for a while() loop. So you could almost have a mind-entry of "Foreach (;;) (c-style loop): See also while()."

    <STDIN> is pretty well documented in perlop. In scalar context it returns one record (or line). In list context, it returns all records (or lines) as separate list elements. In Boolean context it throws a warning under -w.

    I actually think that after reading perlintro, perlsyn, perlop, and perlre you will have just about covered 90% of your context questions. And if you're really interested in Perl you were going to read those anyway. :)


    Dave

Re: Easy Reference for Contexts
by wind (Priest) on Apr 14, 2011 at 07:19 UTC
Re: Easy Reference for Contexts
by ikegami (Patriarch) on Apr 14, 2011 at 15:54 UTC

    Honestly, the answers are usually obvious.

    while( ) i.e. inside parenthesis is evaluated in scalar context?

    It needs a single true/false value. What context do you think it imposes?

    foreach( ) i.e. inside parenthesis is evaluated in list context?

    It iterates over a list. What context do you think it imposes?

    The are two areas of confusions.

    • Where prototypes are involved.

      sub plain { print $_[0]; } sub proto($) { print $_[0]; } my @a = 4; plain(@a); # 4 proto(@a); # 1

      Most builtins have prototypes, so passing an argument list from an array rarely works with them.

    • There are two different assignment operators. One imposes a scalar context on its LHS and RHS operand, while the other imposes list context on its LHS and RHS operands. It should be still be intuitive, but you might want to check out Mini-Tutorial: Scalar vs List Assignment Operator.

Re: Easy Reference for Contexts
by JavaFan (Canon) on Apr 14, 2011 at 10:52 UTC
    There ought to be a repository of common expressions and how they behave in each context
    The perl documentation does that, doesn't it? perlop and perlfunc would be the places to look first.
    what their default context is
    There's no default context. An expression is always in a context. And it's always the caller that determines the context - there's no operator/function that says "you know what, I let my operands run in their default context". (And how could it?)
      > > what their default context is
      > There's no default context.

      with a little more tolerance in interpretation of "context":

      IIRC some operands and builtins only work in special contexts, some even throw (threw?) warnings if not used properly.

      > > There ought to be a repository of common expressions and how they behave in each context
      > The perl documentation does that, doesn't it?

      Well I once meditated over this, unfortunately POD doesn't have a standard notation for a brief definition for the interface of a term.

      If it had, they could not only automatically be compiled into cheat sheets, but also into tool tips for IDEs or grammatical rules for syntax checkers.

      There are various alternative sources for such abstracts, which get hopelessly fast outdated

      For instance emacs's cperl-mode has tool-tips hardcoded which are far from being up-to-date.

      (defvar cperl-short-docs 'please-ignore-this-line ;; Perl4 version was written by Johan Vromans (jvromans@squirrel.nl) "# based on '@(#)@ perl-descr.el 1.9 - describe-perl-symbol' [Perl 5 +] ... Range (list context); flip/flop [no flop when flip] (scalar con +text). ! ... Logical negation. ... != ... Numeric inequality. ... !~ ... Search pattern, substitution, or translation (negated). $! In numeric context: errno. In a string context: error string. $\" The separator which joins elements of arrays interpolated in st +rings. $# The output format for printed numbers. Default is %.15g or clos +e. $$ Process number of this script. Changes in the fork()ed child pr +ocess. $% The current page number of the currently selected output channel +. The following variables are always local to the current block: $1 Match of the 1st set of parentheses in the last match (auto-loca +l). $2 Match of the 2nd set of parentheses in the last match (auto-loca +l). $3 Match of the 3rd set of parentheses in the last match (auto-loca +l). $4 Match of the 4th set of parentheses in the last match (auto-loca +l). $5 Match of the 5th set of parentheses in the last match (auto-loca +l). $6 Match of the 6th set of parentheses in the last match (auto-loca +l). $7 Match of the 7th set of parentheses in the last match (auto-loca +l). $8 Match of the 8th set of parentheses in the last match (auto-loca +l). $9 Match of the 9th set of parentheses in the last match (auto-loca +l). $& The string matched by the last pattern match (auto-local). $' The string after what was matched by the last match (auto-local) +. $` The string before what was matched by the last match (auto-local +). $( The real gid of this process. $) The effective gid of this process. $* Deprecated: Set to 1 to do multiline matching within a string. $+ The last bracket matched by the last search pattern. $, The output field separator for the print operator. $- The number of lines left on the page. $. The current input line number of the last filehandle that was re +ad. $/ The input record separator, newline by default. $0 Name of the file containing the current perl script (read/write) +. $: String may be broken after these characters to fill ^-lines in +a format. $; Subscript separator for multi-dim array emulation. Default \"\\ +034\". $< The real uid of this process. $= The page length of the current output channel. Default is 60 li +nes. $> The effective uid of this process. $? The status returned by the last ``, pipe close or `system'. $@ The perl error message from the last eval or do @var{EXPR} comma +nd. $ARGV The name of the current file used with <> . $[ Deprecated: The index of the first element/char in an array/stri +ng. $\\ The output record separator for the print operator. $] The perl version string as displayed with perl -v. $^ The name of the current top-of-page format. $^A The current value of the write() accumulator for format() line +s. $^D The value of the perl debug (-D) flags. $^E Information about the last system error other than that provid +ed by $!. $^F The highest system file descriptor, ordinarily 2. $^H The current set of syntax checks enabled by `use strict'. $^I The value of the in-place edit extension (perl -i option). $^L What formats output to perform a formfeed. Default is \f. $^M A buffer for emergency memory allocation when running out of m +emory. $^O The operating system name under which this copy of Perl was bu +ilt. $^P Internal debugging flag. $^T The time the script was started. Used by -A/-M/-C file tests. $^W True if warnings are requested (perl -w flag). $^X The name under which perl was invoked (argv[0] in C-speech). $_ The default input and pattern-searching space. $| Auto-flush after write/print on current output channel? Default + 0. $~ The name of the current report format. ... % ... Modulo division. ... %= ... Modulo division assignment. %ENV Contains the current environment. %INC List of files that have been require-d or do-ne. %SIG Used to set signal handlers for various signals. ... & ... Bitwise and. ... && ... Logical and. ... &&= ... Logical and assignment. ... &= ... Bitwise and assignment. ... * ... Multiplication. ... ** ... Exponentiation. *NAME Glob: all objects refered by NAME. *NAM1 = *NAM2 aliases NAM +1 to NAM2. &NAME(arg0, ...) Subroutine call. Arguments go to @_. ... + ... Addition. +EXPR Makes EXPR into scalar context. ++ Auto-increment (magical on strings). ++EXPR EXPR++ ... += ... Addition assignment. , Comma operator. ... - ... Subtraction. -- Auto-decrement (NOT magical on strings). --EXPR EXPR-- ... -= ... Subtraction assignment. -A Access time in days since script started. -B File is a non-text (binary) file. -C Inode change time in days since script started. -M Age in days since script started. -O File is owned by real uid. -R File is readable by real uid. -S File is a socket . -T File is a text file. -W File is writable by real uid. -X File is executable by real uid. -b File is a block special file. -c File is a character special file. -d File is a directory. -e File exists . -f File is a plain file. -g File has setgid bit set. -k File has sticky bit set. -l File is a symbolic link. -o File is owned by effective uid. -p File is a named pipe (FIFO). -r File is readable by effective uid. -s File has non-zero size. -t Tests if filehandle (STDIN by default) is opened to a tty. -u File has setuid bit set. -w File is writable by effective uid. -x File is executable by effective uid. -z File has zero size. . Concatenate strings. .. Range (list context); flip/flop (scalar context) operator. .= Concatenate assignment strings ... / ... Division. /PATTERN/ioxsmg Pattern match ... /= ... Division assignment. /PATTERN/ioxsmg Pattern match. ... < ... Numeric less than. <pattern> Glob. See <NAME>, < +> as well. <NAME> Reads line from filehandle NAME (a bareword or dollar-barewo +rd). <pattern> Glob (Unless pattern is bareword/dollar-bareword - see <N +AME>). <> Reads line from union of files in @ARGV (= command line) and STD +IN. ... << ... Bitwise shift left. << start of HERE-DOCUMENT. ... <= ... Numeric less than or equal to. ... <=> ... Numeric compare. ... = ... Assignment. ... == ... Numeric equality. ... =~ ... Search pattern, substitution, or translation ... > ... Numeric greater than. ... >= ... Numeric greater than or equal to. ... >> ... Bitwise shift right. ... >>= ... Bitwise shift right assignment. ... ? ... : ... Condition=if-then-else operator. ?PAT? One-time p +attern match. ?PATTERN? One-time pattern match. @ARGV Command line arguments (not including the command name - see +$0). @INC List of places to look for perl scripts during do/include/use. @_ Parameter array for subroutines; result of split() unless in lis +t context. \\ Creates reference to what follows, like \$var, or quotes non-\w in + strings. \\0 Octal char, e.g. \\033. \\E Case modification terminator. See \\Q, \\L, and \\U. \\L Lowercase until \\E . See also \\l, lc. \\U Upcase until \\E . See also \\u, uc. \\Q Quote metacharacters until \\E . See also quotemeta. \\a Alarm character (octal 007). \\b Backspace character (octal 010). \\c Control character, e.g. \\c[ . \\e Escape character (octal 033). \\f Formfeed character (octal 014). \\l Lowercase the next character. See also \\L and \\u, lcfirst. \\n Newline character (octal 012 on most systems). \\r Return character (octal 015 on most systems). \\t Tab character (octal 011). \\u Upcase the next character. See also \\U and \\l, ucfirst. \\x Hex character, e.g. \\x1b. ... ^ ... Bitwise exclusive or. __END__ Ends program source. __DATA__ Ends program source. __FILE__ Current (source) filename. __LINE__ Current line in current source. __PACKAGE__ Current package. ARGV Default multi-file input filehandle. <ARGV> is a synonym for +<>. ARGVOUT Output filehandle with -i flag. BEGIN { ... } Immediately executed (during compilation) piece of co +de. END { ... } Pseudo-subroutine executed after the script finishes. CHECK { ... } Pseudo-subroutine executed after the script is compil +ed. INIT { ... } Pseudo-subroutine executed before the script starts ru +nning. DATA Input filehandle for what follows after __END__ or __DATA__ +. accept(NEWSOCKET,GENERICSOCKET) alarm(SECONDS) atan2(X,Y) bind(SOCKET,NAME) binmode(FILEHANDLE) caller[(LEVEL)] chdir(EXPR) chmod(LIST) chop[(LIST|VAR)] chown(LIST) chroot(FILENAME) close(FILEHANDLE) closedir(DIRHANDLE) ... cmp ... String compare. connect(SOCKET,NAME) continue of { block } continue { block }. Is executed after `next' or + at end. cos(EXPR) crypt(PLAINTEXT,SALT) dbmclose(%HASH) dbmopen(%HASH,DBNAME,MODE) defined(EXPR) delete($HASH{KEY}) die(LIST) do { ... }|SUBR while|until EXPR executes at least once do(EXPR|SUBR([LIST])) (with while|until executes at least once) dump LABEL each(%HASH) endgrent endhostent endnetent endprotoent endpwent endservent eof[([FILEHANDLE])] ... eq ... String equality. eval(EXPR) or eval { BLOCK } exec([TRUENAME] ARGV0, ARGVs) or exec(SHELL_COMMAND_LINE) exit(EXPR) exp(EXPR) fcntl(FILEHANDLE,FUNCTION,SCALAR) fileno(FILEHANDLE) flock(FILEHANDLE,OPERATION) for (EXPR;EXPR;EXPR) { ... } foreach [VAR] (@ARRAY) { ... } fork ... ge ... String greater than or equal. getc[(FILEHANDLE)] getgrent getgrgid(GID) getgrnam(NAME) gethostbyaddr(ADDR,ADDRTYPE) gethostbyname(NAME) gethostent getlogin getnetbyaddr(ADDR,ADDRTYPE) getnetbyname(NAME) getnetent getpeername(SOCKET) getpgrp(PID) getppid getpriority(WHICH,WHO) getprotobyname(NAME) getprotobynumber(NUMBER) getprotoent getpwent getpwnam(NAME) getpwuid(UID) getservbyname(NAME,PROTO) getservbyport(PORT,PROTO) getservent getsockname(SOCKET) getsockopt(SOCKET,LEVEL,OPTNAME) gmtime(EXPR) goto LABEL ... gt ... String greater than. hex(EXPR) if (EXPR) { ... } [ elsif (EXPR) { ... } ... ] [ else { ... } ] or EXP +R if EXPR index(STR,SUBSTR[,OFFSET]) int(EXPR) ioctl(FILEHANDLE,FUNCTION,SCALAR) join(EXPR,LIST) keys(%HASH) kill(LIST) last [LABEL] ... le ... String less than or equal. length(EXPR) link(OLDFILE,NEWFILE) listen(SOCKET,QUEUESIZE) local(LIST) localtime(EXPR) log(EXPR) lstat(EXPR|FILEHANDLE|VAR) ... lt ... String less than. m/PATTERN/iogsmx mkdir(FILENAME,MODE) msgctl(ID,CMD,ARG) msgget(KEY,FLAGS) msgrcv(ID,VAR,SIZE,TYPE.FLAGS) msgsnd(ID,MSG,FLAGS) my VAR or my (VAR1,...) Introduces a lexical variable ($VAR, @ARR, +or %HASH). our VAR or our (VAR1,...) Lexically enable a global variable ($V, @A, +or %H). ... ne ... String inequality. next [LABEL] oct(EXPR) open(FILEHANDLE[,EXPR]) opendir(DIRHANDLE,EXPR) ord(EXPR) ASCII value of the first char of the string. pack(TEMPLATE,LIST) package NAME Introduces package context. pipe(READHANDLE,WRITEHANDLE) Create a pair of filehandles on ends o +f a pipe. pop(ARRAY) print [FILEHANDLE] [(LIST)] printf [FILEHANDLE] (FORMAT,LIST) push(ARRAY,LIST) q/STRING/ Synonym for 'STRING' qq/STRING/ Synonym for \"STRING\" qx/STRING/ Synonym for `STRING` rand[(EXPR)] read(FILEHANDLE,SCALAR,LENGTH[,OFFSET]) readdir(DIRHANDLE) readlink(EXPR) recv(SOCKET,SCALAR,LEN,FLAGS) redo [LABEL] rename(OLDNAME,NEWNAME) require [FILENAME | PERL_VERSION] reset[(EXPR)] return(LIST) reverse(LIST) rewinddir(DIRHANDLE) rindex(STR,SUBSTR[,OFFSET]) rmdir(FILENAME) s/PATTERN/REPLACEMENT/gieoxsm scalar(EXPR) seek(FILEHANDLE,POSITION,WHENCE) seekdir(DIRHANDLE,POS) select(FILEHANDLE | RBITS,WBITS,EBITS,TIMEOUT) semctl(ID,SEMNUM,CMD,ARG) semget(KEY,NSEMS,SIZE,FLAGS) semop(KEY,...) send(SOCKET,MSG,FLAGS[,TO]) setgrent sethostent(STAYOPEN) setnetent(STAYOPEN) setpgrp(PID,PGRP) setpriority(WHICH,WHO,PRIORITY) setprotoent(STAYOPEN) setpwent setservent(STAYOPEN) setsockopt(SOCKET,LEVEL,OPTNAME,OPTVAL) shift[(ARRAY)] shmctl(ID,CMD,ARG) shmget(KEY,SIZE,FLAGS) shmread(ID,VAR,POS,SIZE) shmwrite(ID,STRING,POS,SIZE) shutdown(SOCKET,HOW) sin(EXPR) sleep[(EXPR)] socket(SOCKET,DOMAIN,TYPE,PROTOCOL) socketpair(SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL) sort [SUBROUTINE] (LIST) splice(ARRAY,OFFSET[,LENGTH[,LIST]]) split[(/PATTERN/[,EXPR[,LIMIT]])] sprintf(FORMAT,LIST) sqrt(EXPR) srand(EXPR) stat(EXPR|FILEHANDLE|VAR) study[(SCALAR)] sub [NAME [(format)]] { BODY } sub NAME [(format)]; sub [(format +)] {...} substr(EXPR,OFFSET[,LEN]) symlink(OLDFILE,NEWFILE) syscall(LIST) sysread(FILEHANDLE,SCALAR,LENGTH[,OFFSET]) system([TRUENAME] ARGV0 [,ARGV]) or system(SHELL_COMMAND_LINE) syswrite(FILEHANDLE,SCALAR,LENGTH[,OFFSET]) tell[(FILEHANDLE)] telldir(DIRHANDLE) time times tr/SEARCHLIST/REPLACEMENTLIST/cds truncate(FILE|EXPR,LENGTH) umask[(EXPR)] undef[(EXPR)] unless (EXPR) { ... } [ else { ... } ] or EXPR unless EXPR unlink(LIST) unpack(TEMPLATE,EXPR) unshift(ARRAY,LIST) until (EXPR) { ... } EXPR until EXPR utime(LIST) values(%HASH) vec(EXPR,OFFSET,BITS) wait waitpid(PID,FLAGS) wantarray Returns true if the sub/eval is called in list context. warn(LIST) while (EXPR) { ... } EXPR while EXPR write[(EXPR|FILEHANDLE)] ... x ... Repeat string or array. x= ... Repetition assignment. y/SEARCHLIST/REPLACEMENTLIST/ ... | ... Bitwise or. ... || ... Logical or. ~ ... Unary bitwise complement. #! OS interpreter indicator. If contains `perl', used for options, + and -x. AUTOLOAD {...} Shorthand for `sub AUTOLOAD {...}'. CORE:: Prefix to access builtin function if imported sub obscur +es it. SUPER:: Prefix to lookup for a method in @ISA classes. DESTROY Shorthand for `sub DESTROY {...}'. ... EQ ... Obsolete synonym of `eq'. ... GE ... Obsolete synonym of `ge'. ... GT ... Obsolete synonym of `gt'. ... LE ... Obsolete synonym of `le'. ... LT ... Obsolete synonym of `lt'. ... NE ... Obsolete synonym of `ne'. abs [ EXPR ] absolute value ... and ... Low-precedence synonym for &&. bless REFERENCE [, PACKAGE] Makes reference into an object of a pac +kage. chomp [LIST] Strips $/ off LIST/$_. Returns count. Special if $/ +eq ''! chr Converts a number to char with the same ordinal. else Part of if/unless {BLOCK} elsif {BLOCK} else {BLOCK}. elsif Part of if/unless {BLOCK} elsif {BLOCK} else {BLOCK}. exists $HASH{KEY} True if the key exists. format [NAME] = Start of output format. Ended by a single dot (.) + on a line. formline PICTURE, LIST Backdoor into \"format\" processing. glob EXPR Synonym of <EXPR>. lc [ EXPR ] Returns lowercased EXPR. lcfirst [ EXPR ] Returns EXPR with lower-cased first letter. grep EXPR,LIST or grep {BLOCK} LIST Filters LIST via EXPR/BLOCK. map EXPR, LIST or map {BLOCK} LIST Applies EXPR/BLOCK to elts of + LIST. no PACKAGE [SYMBOL1, ...] Partial reverse for `use'. Runs `unimport' + method. not ... Low-precedence synonym for ! - negation. ... or ... Low-precedence synonym for ||. pos STRING Set/Get end-position of the last match over this string, + see \\G. quotemeta [ EXPR ] Quote regexp metacharacters. qw/WORD1 .../ Synonym of split('', 'WORD1 ...') readline FH Synonym of <FH>. readpipe CMD Synonym of `CMD`. ref [ EXPR ] Type of EXPR when dereferenced. sysopen FH, FILENAME, MODE [, PERM] (MODE is numeric, see Fcntl.) tie VAR, PACKAGE, LIST Hide an object behind a simple Perl variable +. tied Returns internal object for a tied data. uc [ EXPR ] Returns upcased EXPR. ucfirst [ EXPR ] Returns EXPR with upcased first letter. untie VAR Unlink an object from a simple Perl variable. use PACKAGE [SYMBOL1, ...] Compile-time `require' with consequent `im +port'. ... xor ... Low-precedence synonym for exclusive or. prototype \&SUB Returns prototype of the function given a reference +. =head1= Top-level heading. =head2= Second-level heading. =head3= Third-level heading (is there such?). =over= [ NUMBER ] Start list. =item= [ TITLE ] Start new item in the list. =back= End list. =cut= Switch from POD to Perl. =pod= Switch from Perl to POD. ")

      Another advantage of such an hypothetical POD-extension could be the definition of use cases for snippet-expansion within an IDE, like for yasnippet in emacs or more detailed error-texts for diagnostics.

      Of course some (all?) of this could be achieved with a special =FOR :format-paragraph, but there is no standard notation yet. (maybe Perl6 signatures could be a good start)

      Cheers Rolf

        Padre/../PPI? B::Deparse::ContextAnnotate? Perl::Tidy::ContextAnnotate?

        Hmm ... delicious ideas .... ...

        … … … .__,,,_._,--~~~~~---,,_
        … … ,,-"… .,~". . . . . . . . . . . . ."~-,
        … …,/-~-,-". . . . . . . . . . . . . . . . . . ."~,,___
        … ,-".|..,-". . . . . . . . . . . . . . . . . . . . . . . . .~'~--,,_
        ... /… \". . . . . . . . . . . . . . . . . . . . . . . . . . . . . __,'\
        … \..,/."-. . . . . . . . . . . . . . . . . . . . . ."~,,. .,,-~'--': : |
        … ."-'. . . . . . . . . . . . . . . . . . . . . . ._,,-~'\": : :,~"``"~,
        … ..|.". . . . . . . . . . . . . . . . . . . ,-,": : : : : :|:,,-". . . . . |
        … ..|. . . . . . . . . . . . . . \. . . . ,-"~': : : : : : /. . . . . . . ./~---,,_
        … ...\. . . . . . . . . . . . . . \. . ,-": : : : : : : : /. . . . . ,-~"'………."~-,
        … … '\. . . . . . . . . . . . . .",": : : : : : : _,-". . . ,-~"…………………"\
        … … .."-,. . . ,_. . . . . . . . ―"~~----~". . . ,-~"…………….._,,--~,,../
        … … … ."~,. . \,"~,_. . . . . . . . . . . . . .,-"……………,,~": :,,,-,'~',/
        … … … … ,",-,. "-,. ."~. . . . . . . . . . ,-"………….,~":,,,,,--":,-".,-"
        … … … … ."-,.."~,". _,. . . . . . . . . ,/…………,~": ,-",-"_,"".,-"
        … … … … … \… ,-". __, . . . . . . ,/………...,-": ,"';/―,"…,~"
        … … … … … … .\. .".\. . .,. . . . ./……….,-"_,,-";;;\,/..,-"
        … … … … … … ..."~~-,--". . . ./………,-": /;;;;;;;;;/../
        … … … … … … … … .|. . . . . |……..,/~~';;;;;;;;;;;|...'\,
        … … … … … … … … .|. . . . . |……./;,-~~--,-~~-,"-….|
        … … … … … … … … .|. . . . . .\…...|-"::::::::":::::::\... |
        … … … … … … … .SL|. . . . . . \,….."--,--"-,:::::::::/..,/
        … … … … … … … … .|. . . . . . . "~,……――"~--~"..,/
        … … … … … … … … .|. . . . . . . . . ."~~---,,,,,,--~"\
        … … … … … … … … ..――"'~~~~---------,,,,,,,,,_____\
        ---
Re: Easy Reference for Contexts
by Anonymous Monk on Apr 14, 2011 at 10:01 UTC
Re: Easy Reference for Contexts
by LanX (Saint) on Apr 14, 2011 at 13:42 UTC
    m/.../ returns true or false in scalar context m/.../g give you a list of matches in list context m/(...)/ can populate an array with whatever gets captured... (??) while( ) i.e. inside parenthesis is evaluated in scalar context? foreach( ) i.e. inside parenthesis is evaluated in list context? <STDIN> returns the next line of input in list context

    Well ... most of this can be tested interactively.

    The inside context with wantarray the outside context behavior with print, print scalar and a void call.

    For instance I doubted that scalar m// returns true or false (those identifiers don't exist in Perl), I thought it's the number of matches returned.

    But I was wrong: :)

    DB<23> $_="aaa" DB<24> print scalar m/a/ 1

    Cheers Rolf

    UPDATE: Forgot to mention, you can also check the prototype for most builtins:

    perl -e 'print prototype "CORE::push","\n"' \@@
    which is more complex than just void, list and scalar... check out perlsub for details.

    And some builtins (like map) have such a "rich" syntax that they can't be expressed with prototypes.

      For instance I doubted that scalar m// returns true or false (those identifiers don't exist in Perl), I thought it's the number of matches returned.

      But I was wrong: :)

      DB<23> $_="aaa" DB<24> print scalar m/a/ 1
      Anything in Perl is true or false. Or rather, ANYTHING is true but undef is false. 😋

      Like the relops, m//, s///, and y/// can all return the magical false value, that secret special value that nobody talks about:

      % perl -wle 'printf "got %d matches\n", scalar ANYTHING =~ /nothing/'
      got 0 matches
      So I shan’t, either. 😜
        > Or rather, ANYTHING is true but undef is false.

        Many things in Perl are evaluated to false in boolean context, not only undef.

        Cheers Rolf

Re: Easy Reference for Contexts
by dmn001 (Initiate) on Apr 14, 2011 at 23:17 UTC
    I sometimes refer to this:

    http://www.cs.tut.fi/~jkorpela/perl/regexp.html

    for regex reference.

    And the book Learning Perl is a great help too.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://899364]
Approved by philipbailey
Front-paged by philipbailey
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (6)
As of 2024-04-16 08:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found