Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

RE: variable comparison

by Simplicus (Monk)
on May 25, 2000 at 18:03 UTC ( [id://14758]=note: print w/replies, xml ) Need Help??


in reply to variable comparison

If all you are trying to do is determine the extension of a file, you can use the function
substr string, pos, [n, replacement]

which extracts and returns a substring n characters long, starting at position pos, from a given string. If pos is negative, the substring starts at the end of the string instead, so something like:
my $ext = ".htm"; my $filename = "filename.htm"; if ($ext eq substr ($filename, -4)) { #whatever } else { #whatever else }

Also, substr can be put to more interesting uses. consider:
  • if n is omitted, everything to the end of the string is included.
  • if n is negative, that many chars are left off the end of the string.


For more information, consult Perl in a Nutshell,
ISBN 1-56592-286-7, published by O'Rielly.
Simplicus

Replies are listed 'Best First'.
RE: RE: variable comparison
by mdillon (Priest) on May 25, 2000 at 19:38 UTC
    i like the substr approach myself, although i would make the small change of using the length function instead of hard coding the length of $ext.
    if (substr($filename, -length($ext)) eq $ext) { # do stuff } else { # do other stuff }
      Agreed. I've been brainwashed by Redmond to assume that an
      extension is three characters long. My early DOS training
      is to blame for that. (good ol' 8.3 notation, you know?)

      Using a regex to hunt for the dot is out of the question,
      because you might have a filename "foo.bar.htm" for example.
      Of course, you could always look for the last instance of
      the . in the filename, but . . . in the interst of having
      clearer code, I like the substr approach better than the
      regex (if only this once ;-) )
        for finding the last instance of a string in another string, you can use rindex.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://14758]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (5)
As of 2024-04-25 11:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found