Trying to understand this piece of code

--Next_1091445263---0-202.54.124.130-2524
Content-type: text/plain;
	charset=iso-8859-1
Content-Transfer-Encoding: quoted-printable
Content-Disposition: inline

 =A0=0AHi=0A=0ACan someone please tell me what the following code is trying=
 to do =0A=0A=0A      if ( /CR List/ .. /\(2\)/ ) {=0A         if ( /CR Lis=
t/ )  { print " $'\n"; }=0A         elsif ( /\(2\)/ ) {print " $` \n" ;}=0A=
         else              { print "            $_\n";}=0A        }=0A=0AI =
know that it is trying to print whatever is there between CR List and (2). =
But i am not able guess more than that. =0A=0ARegards=0ASudhindra=0A=0A
--Next_1091445263---0-202.54.124.130-2524--

0
sudhindra_k_s
8/2/2004 11:14:23 AM
perl.beginners 29319 articles. 3 followers. Follow

3 Replies
213 Views

Similar Articles

[PageSpeed] 57

From: "sudhindra k s" <sudhindra_k_s@rediffmail.com>
> Can someone please tell me what the following code is trying to do 
> 
>       if ( /CR List/ .. /\(2\)/ ) {
>          if ( /CR List/ )  { print " $'\n"; }
>          elsif ( /\(2\)/ ) {print " $` \n" ;}
>          else              { print "            $_\n";}
>         }
> 
> I know that it is trying to print whatever is there between CR List
> and (2). But i am not able guess more than that. 

The magic is in the .. operator. It returns false until the first 
operand evaluates to true, then it returns true until after the  
second operand evaluates to true, then again false until the first 
becomes true ...

Let me give you a simpler example:

foreach my $var (1,2,3,4,5,6,7,8,9) {
	if ($var == 3 .. $var == 6) {
		print "$var\n";
	}
}


The operator works like the following code:

my $_status = 1;
foreach my $var (1,2,3,4,5,6,7,8,9) {
	if ($_status == 1) {
		if ($var == 3) {
			$_status = 2;
			print "$var\n";
		}
	} else {
		print "$var\n";
		if ($var == 6) {
			$_status = 1;
		}
	}
}

HTH, Jenda
===== Jenda@Krynicky.cz === http://Jenda.Krynicky.cz =====
When it comes to wine, women and song, wizards are allowed 
to get drunk and croon as much as they like.
	-- Terry Pratchett in Sourcery

0
Jenda
8/2/2004 11:58:03 AM
sudhindra k s wrote:
> Hi
> 
> Can someone please tell me what the following code is trying to do
> 
> 
>       if ( /CR List/ .. /\(2\)/ ) {
>          if ( /CR List/ )  { print " $'\n"; }
>          elsif ( /\(2\)/ ) {print " $` \n" ;}
>          else              { print "            $_\n";}
>         }
> 
> I know that it is trying to print whatever is there between CR List
> and (2). But i am not able guess more than that. 

The $' and $` are builtin Perl variables. They are documented in 

   perldoc perlvar

$' is the text following the last successful match (i.e. the stuff on the
line to the right of "CR List"). $` is the text preceeding the last
successful match (the stuff on the line to the left of "(2)")
0
Bob_Showalter
8/2/2004 2:39:32 PM
On Mon, 2 Aug 2004, Bob Showalter wrote:

> sudhindra k s wrote:
>> Hi
>>
>> Can someone please tell me what the following code is trying to do
>>
>>
>>       if ( /CR List/ .. /\(2\)/ ) {
>>          if ( /CR List/ )  { print " $'\n"; }
>>          elsif ( /\(2\)/ ) {print " $` \n" ;}
>>          else              { print "            $_\n";}
>>         }
>>
>> I know that it is trying to print whatever is there between CR List
>> and (2). But i am not able guess more than that.
>
> The $' and $` are builtin Perl variables. They are documented in
>
>   perldoc perlvar
>
> $' is the text following the last successful match (i.e. the stuff on 
> the line to the right of "CR List"). $` is the text preceeding the 
> last successful match (the stuff on the line to the left of "(2)")

And according to several reliable sources of documentation, notably 
_Mastering Regular Expressions_, they should *never be used*.

The presence of these variables anywhere in your code changes the 
pattern matching strategy that Perl uses in such a way that performance 
is much, much worse than normal in most cases.

The whys and hows of this are complicated -- it's worth reading _MRE_. 
The short version is that you should almost always replace code that 
uses $`, $&, or $' with functionally equivalent code that gets the same 
result without using these variables. For example, this code could be:

        if ( /CR List(.*)/ .. /(.*)\(2\)/ ) {
           if ( /CR List/ )  { print " $1\n"; }
           elsif ( /\(2\)/ ) { print " $1 \n" ;}
           else              { print "            $_\n";}
        }

....or something to that effect.



Of course, it could be that more recent versions of Perl have fixed this 
problem and I'm not aware of it. If so, please correct me :-)



-- 
Chris Devers
0
cdevers
8/2/2004 3:04:55 PM
Reply:

Similar Artilces:

Trying to understand existing code
I hope to understand these existing code (3 lines) here. Can someone help me to explain these few lines here? Example, what is the meaning of defaultview here?1 dstUser = New DataSet 2 dadUser.Fill(dstUser, "tableA") 3 4 Return dstUser.Tables("tableA").DefaultView   My HomePage - www.findingsteve.net"It is more blessed to give than to receive." Acts 20: 35 (NIV, Bible)Progress - "Never discourage anyone...who continually makes progress, no matter how slow." Plato Hi, the DefaultView property returns a DataView on tableA. Y...

beginner trying to parse a piece of mail
I have had success now using Mail::MboxParser for all my basic mail parsing needs, like getting subject, from, to. Now bossman wants me to do more extensive regex filtering and grabbing weird data in the email body. I wrote a little test script, shown below. I am able to get the "appointment date" data, contained in the message body, that I am looking for, but only for the first record. The while loop keeps looping back to that record. Also, I cannot get to the next line that has the "comments section" for each email. I know this has got to be something stupid...

Trying to understand the structure of the Mozilla code
Hi! I'm trying to develope some alternatives to the junk filtering system but I can't find a place where the code is explained. Would anybody help me, please?. C�sar Garc�a wrote: > Hi! > I'm trying to develope some alternatives to the junk filtering system > but I can't find a place where the code is explained. > Would anybody help me, please?. > Garcia, Do you interested into building a anti-spam plug-in feature for mozilla mail? Please let me know. I am trying to get a few guys together help me to make the project intoreality. Of course, ...

Need help understanding piece of Javascript code
 Hello all, I have an http chat page in which I have simulated a persistent communication enviornment. I discovered the javascript code I had been using to detect when a person left the chat page was not working when a user closed out their browser. I found the code below to correct this problem and from a functional standpoint it works as desired, well almost. The message the user receives upon exiting the chat page is not as I would like. I need help understanding how to modify my javascript so that one of two things happens. First, a message that simply indicates to the ...

I'm trying to see what a piece of code does?
What is this piece of code for? <system.net> <mailSettings> <smtp deliveryMethod="Network"> <network defaultCredentials="true" host="vsnetbeta2" port="25" from="Webmaster@FineLine.com"></network> </smtp> </mailSettings> </system.net> That specifies the default mail server - port - and from address, as well as the transport, for certain controls and code segments in .net 2.0, like the create user wizard, and the forgot your password user control - possibly a few others.   Bryan SampicaAuction Site StarterKit |My Blog...

Trying to Understand Code pages, why does filtering fail ?
I built a database using codepage 437 (US). I'm trying to run it in Arabic Enabled NT. There are Arabic characters in the Database. I cannot filter on the Arabic characters. I can filter on the english characters. Anyone have any ideas. In reading through the documentation on collation and international support in Adaptive Server Anywhere, I found reference default supplied code page support. It appears that the Arabic code pages (Group 6, CP864, CP1256, ISO8859-6) is not supplied. Could this be the reason why filtering does not work ? On Arabic NT. Am I configuring ODBC ...

Trying to understand 2-way databinding
Why doesn't this work? <asp:SqlDataSource Runat = "server" id = "srcGuestList" ConnectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True" SelectCommand = "SELECT * FROM GuestList" InsertCommand = "INSERT INTO GuestList (first_name) VALUES('@first_name')" ProviderName="System.Data.SqlClient" /> <asp:GridView id = "guestList" Runat = "server" ...

help with password code (understanding the code)
I have a question regarding the following code: <modify-attr attr-name="nspmDistributionPassword"> <!-- content suppressed --> </modify-attr> The "<!-- content suppressed --> " is the value correct? Is it multi value? because how does it store more than one item, as I also trying to figure out how the !-- content suppressed --> is then passed into the destination password. How does it refernece this part to put it as the password. Can someone please xplain the following? ADDriver ST: Applying rule 'Convert mo...

Trying to understand
Ok, I'm been trying to understand the new ADO.net thing, and it seems pretty simple, as long as your using databound controls.Unfortunatly, I have a lot of pages that I can just ad a grid view to and make the things look right, so I'm trying to understand how to programatically access ADO.net.Below is an example of some of the simplest code I need to convert and any help would be aprreciated.set connectionToDatabase=server.createobject("adodb.connection")connectionToDatabase.connectiontimeout=60connectionToDatabase.open "DSN=ServiceCalls"set rc=server.CreateObject...

trying and trying
Name: otto de koningh Email: ottodotdedotkoninghatskynetdotbe Product: Firefox Release Candidate Summary: trying and trying Comments: what a weird robot !! please refrain from using these horrendous figures i like the motorcycle though shown on the add-ons page i am having trouble because there is an unknown dump on firefox - never encountered this ! your browser is otherwise top of the bill !! from Firefox Setup 1.5.0.3 onwards in May 2006 Firefox has become a true companion ! now with Firefox Setup 3.0 RC1 i have error reports ! how come ? Browser Details: Mozilla/5.0 (...

Understanding the code?
Hi Just trying to teach myself ASP.NET code using VB from a book called "ASP.NET For Dummies". This seems to be quite a good book for me to follow, especially with me having very little experience of any kind of programming. I'm trying desperately to understand as much as I can rather than just accept certain blocks of code as, "this is just the way it works" type of thing. There is a line of code in the book that I cannot get my head around as the book doesn't fully explain why it is written the way it is. The block of code is: If Category <> "&...

understanding code
Hi all, Can any one walk me thru this piece of code :: while(<STDIN>) { chomp ; $isbn =(split(/^_/, $_))[0] ; --- not able to understand what is being accessed (......)[0] unless ($KEYS{$isbn} ) ---- isbn is a scalar variable, how keys wok on it ? { print "$_\n" ; $KEYS{$isbn} =1 ; } } Thanks, Hi, Nilay Puri, Noida wrote: >Hi all, > >Can any one walk me thru this piece of code :: > >while(<STDIN>) >{ > chomp ; > $isbn =3D(split(/^_/, $_))[0] ; --- not able to understand what is >being ac...

Problem trying to import global.asax code from code behind
Hi guys, I have been trying to import the contents of my global.asax file from my compiled code behind dll (The reason I am doing this is because I want to call a shared sub routine that is part of the dll), but when I try to run any of the pages on my site I get the following error: 'Gulf.Global' is not a valid base class because it does not extend class 'System.Web.HttpApplication'. My Global.asax file looks like this: <%@ Application Inherits="Gulf.Global"%> ANd my code behind looks like this: PUBLIC CLASS Global Inherits System.Web.UI.P...

Do not understand this code..
Hi everyone, i have some doubts in this few lines of codes below. could anyone please provide an explannation or adivce for this codes below? thanks very very much..function togglePicture(sender, imgid, srcvalue) {   if (sender.innerText=='Enlarge')  {      sender.innerText='Thumbnail';       window.document.getElementById(imgid).src='images/large/'+srcvalue;    } else {       sender.innerText='Enlarge';       window.document.getElementById(imgid).s...

Web resources about - Trying to understand this piece of code - perl.beginners

Resonate Social For Facebook Helps Advertisers Understand Users’ Motivations
Why do Facebook users make the decisions they make? Resonate wants to help advertisers find out, so the digital marketing outfit launched Resonate ...

Facebook PMD Gigya releases Consumer Insights to better understand user identities
... allows marketers to easily query Gigya’s Identity Storage database and tie identity information with key performance indicators to understand ...

Genius — Search and understand the meaning of song lyrics, poetry, literature, and news on the App Store ...
Get Genius — Search and understand the meaning of song lyrics, poetry, literature, and news on the App Store. See screenshots and ratings, and ...

All sizes - Most people do not listen with the intent to understand; they listen with the intent to reply ...
Flickr is almost certainly the best online photo management and sharing application in the world. Show off your favorite photos and videos to ...

"Understands" - YouTube
If Mitt Romney wins, the middle class loses. (Priorities USA Action is responsible for the content of this advertising)

Scientists continue search to understand Mers
The Mers coronavirus continues to confound scientists. To better understand the disease and determine where it comes from, a new project set ...

Explainer Video of the Day: Author John Green Helps You Understand Boko Haram
... in the news, but the situation in Nigeria with the Islamist terrorist group Boko Haram often gets overlooked and can be difficult to understand. ...



Businesses don't understand FTAs, so how will they deal with the TPP?
The government is keen to negotiate free trade agreements to bolster economic activity, but new research shows it has its work cut out to educate ...

Resources last updated: 11/30/2015 1:52:52 AM