Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Understanding $1 1

Status
Not open for further replies.

rvBasic

Programmer
Oct 22, 2000
414
0
0
BE
The following script

[blue]$_="1234 56 752";
@x=$_=~m/(\d*)/;
print "\$1=$1 ,\$x[0]=$x[0] and \@x=@x\n";[/blue]

produces an output

[blue]$1=1234 ,$x[0]=1234 and @x=1234[/blue]

just as I expected from the documentation. But when I did a global match like

[blue]$_="1234 56 752";
@x=$_=~m/(\d*)/[red]g[/red];
print "\$1=$1 ,\$x[0]=$x[0] and \@x=@x\n";[/blue]

no value was attached to $1:

[blue]$1= ,$x[0]=1234 and @x=1234 56 752[/blue]

Can somebody explain the behaviour of $1 in this context?

_________________________________
In theory, there is no difference between theory and practice. In practice, there is. [attributed to Yogi Berra]
 
Even more bizarre is that when I limit the greediness of the * quantifier the $x[0] also seems empty, even if the array is not!

[blue]$_="1234 56 752";
@x=$_=~m/(\d*?)/g;
print "\$1=$1 ,\$x[0]=$x[0] and \@x=@x\n";[/blue]

resulting in:

[blue]$1= ,$x[0]= and @x= 1 2 3 4 5 6 7 5 2[/blue]

_________________________________
In theory, there is no difference between theory and practice. In practice, there is. [attributed to Yogi Berra]
 
The problem is that the asterisk matches zero or more times: try with '+' and you'll see a clearer picture.
When g is in effect $1 contains the last match (so nothing if you use *) and [tt]@x[/tt] contains 6 matches, the three numbers plus once (null match) at the end of each number (beacause you said you accept zero figures).
If you use ?, then it matches every figure separately, and also a supplementary null match between each figure because you accept to match 0 times!

Franco
: Online tools for structural design
: Magnetic brakes for fun rides
: Air bearing pads
 
Thanks prex1, that wasmost useful.

Now that I know your explanation, I observe that there is slightly more space between 4 and 5 than between 1 and 2. This is also the case between = and the first figure for @x (as compared to the first posted code). This should correspond to the null match you speak of.

Thanks again.

_________________________________
In theory, there is no difference between theory and practice. In practice, there is. [attributed to Yogi Berra]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top