简体   繁体   中英

Perl expressions in command line - renaming files

Could anyone explain the occurence of our ?

ls -1 | grep .ppm | xargs rename -n 's/.*/our $i; if(!$i) { $i=1; } sprintf("%03d.jpg", $i++)/e'

I tried changing our anything else, ( opti , here),

ls -1 | grep .ppm | xargs rename -n 's/.*/opti $i; if(!$i) { $i=1; } sprintf("%03d.jpg", $i++)/e'

throws following error:

 Global symbol "$i" requires explicit package name at (user-supplied code).

It looks like it's allowing you to reuse the global variable $i in the scope of the current renaming operation.

If it is not yet defined (ie the first file), $i is set to 1 .

The $i++ used as an argument to sprintf means that for every file that is processed, the value of $i increases.

See our in the perl docs for a full description. The key here is that each rename is happening within a loop, so our is needed to make the definition global to the whole script, rather than local to within the loop. This means that means that the same variable is shared between iteration of the loop, so the counter isn't reset each time.

The code is apparently compiled within scope of use strict; . This, among other things, enforces the declaration of variables.

Variables are commonly declared using my , making them lexical variables. A lexical variable only exists until the end of the curly braces in which the variable is declared, or until the end of the replacement "expression" in this case.

Much more rarely, variables are declared using our . This makes them package variables. These continue to exist even when the current lexical scope is exited. This allows $i to keep its value between invocations of the replacement expression.


By the way,

s/.*/our $i; if(!$i) { $i=1; } sprintf("%03d.jpg", $i++)/e

could be shortened to

s/.*/our $i; sprintf("%03d.jpg", ++$i)/e

or even

s/.*/sprintf("%03d.jpg", ++(our $i))/e

or even

s/.*/sprintf("%03d.jpg", ++$::i)/e

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM