Wednesday, May 09, 2012

%1, \1, and $1

Hello friends,when used in a command line, script, or batch file a %1 is used to represent a variable or matched string. For example, in a Microsoft batch file %1 can be used to print what is entered after the batch file name. In the below example of a batch file using the %1, the batch file will print "Hello xxxx it's nice to meet you", where xxxx is whatever you enter after the name of the batch files. So, if this batch file was named example.bat and you typed "example Nathan" the batch file would return Hello Nathan it's nice to meet you.


@echo off
if "%1"=="" goto error
echo Hello %1 it's nice to meet you
goto end
:error
echo Type your name after batch file.
:end


In other programming languages and script languages the %1 may be substituted for \1 or $1. For example, in Perl these could be used in a regular expression to print out the matched text or be used as a new variable. In the below example if the $text variable contains any text at it will print "Hello xxxx" where xxxx is what is matched. So, if $text = "Joe Smith" the script would return "Hello Joe".

 if ($text =~ s/^([a-z]+)/i) {
print "Hello $1\n";
}

Each of these matched strings or variables can also be extended upon by increasing the value. For example, the next matched string or variable found could be entered in as %2, \2, or $2.


Thanks Friends......

No comments:

Post a Comment

Please Give Me Your Views

Popular Posts