functional Ruby equiv to this perl snippet 
Author Message
 functional Ruby equiv to this perl snippet

# parses a text file looking for server names and ignoring lines
# with start with the pound/hash sign.

sub load_server_list {
    $filename = "serverlist.txt";
    open (SERVERLIST, $filename) or die "Can't open $filename:$!";

        $i = 0;
           while (defined ($servername = <SERVERLIST>)) {
             if ($servername ne "\n") {
                if (substr($servername,0,1) ne "#") {
                  chomp ($servername);
                  $servers[$i] = "$servername";
                  $i = $i + 1;
                }
             }
        }
        close (SERVERLIST);
        $server_count = $i;

Quote:
}

I am trying to convert a perl script I like to Ruby and I am not very
good at either!

Thanks!

Bob



Sat, 09 Apr 2005 00:51:51 GMT  
 functional Ruby equiv to this perl snippet

Quote:

> # parses a text file looking for server names and ignoring lines
> # with start with the pound/hash sign.

It's pretty bad Perl, so here it is translated into pretty bad Ruby...

def load_server_list
    filename = "serverlist.txt"
    file = open(filename, "r")
    servers = []
    while line = file.gets
        line.chop!
        next unless line =~ /\S/
        next if line =~ /^#/
        servers << line
    end
    file.close
    return servers
end

--
<TorgoX> EFNet is like one big adverti{*filter*}t for lobotomies.



Sat, 09 Apr 2005 01:04:27 GMT  
 functional Ruby equiv to this perl snippet
Bob said:

Quote:
> # parses a text file looking for server names and ignoring lines
> # with start with the pound/hash sign.

> sub load_server_list {
>     $filename = "serverlist.txt";
>     open (SERVERLIST, $filename) or die "Can't open $filename:$!";

>  $i = 0;
>            while (defined ($servername = <SERVERLIST>)) {
>       if ($servername ne "\n") {
>   if (substr($servername,0,1) ne "#") {
>                   chomp ($servername);
>                   $servers[$i] = "$servername";
>     $i = $i + 1;
>   }
>       }
>         }
>  close (SERVERLIST);
>  $server_count = $i;
> }

Something like this:

def load_server_list(filename)
  server_list = []
  File.open(filename,"r") { |file|
    while file.gets
      next if ~ /^#/
      ~ /^(.*)$/
      server_list << $1.chomp
    end
  }
  return server_list
end

should work, but I didn't try it. =)



Sat, 09 Apr 2005 01:11:35 GMT  
 functional Ruby equiv to this perl snippet

B> # parses a text file looking for server names and ignoring lines
B> # with start with the pound/hash sign.

 and ignoring empty lines, no ?

B> I am trying to convert a perl script I like to Ruby and I am not very
B> good at either!

 Something like this, it return an array

   def load_server_list(filename)
      servers = []
      IO.foreach(filename) do |line|
         next if line[0] == ?# || line[0] == ?\n
         servers << line.chomp
      end
      servers
   rescue
      raise "Can't open #{filename} : #$!"
   end

 to use it

  servers = load_server_list("serverlist.txt")

 servers.size will give the same than $server_count

Guy Decoux



Sat, 09 Apr 2005 01:14:34 GMT  
 functional Ruby equiv to this perl snippet
def load_server_list
    $server_count = 0
    $servers = []
    File.open('serverlist.txt').each do |line|
        next if line =~ /^$/
        next if line =~ /^#.*$/
        $servers << line.chomp.sub(/\s+#.*$/, '')
        $server_count += 1
    end
end

load_server_list
p $server_count
p $servers

This has the added ability to remove comments after server names. My
sample serverlist.txt contained the following:

server1
#server2
server3

#server4
server5
server6 # comment after

An alternative implementation that doesn't use global variables is as
follows:

def load_server_list
    server_count = 0
    servers = []
    File.open('serverlist.txt').each do |line|
        next if line =~ /^$/
        next if line =~ /^#.*$/
        servers << line.chomp.sub(/\s+#.*$/, '')
        server_count += 1
    end
    [server_count, servers]
end

(server_count, servers) = load_server_list
p server_count, servers

-austin



Sat, 09 Apr 2005 01:15:25 GMT  
 functional Ruby equiv to this perl snippet
I realised that my first test wasn't good for non-empty but blank
lines. The following fixes that. Also note that I've removed
server_count -- you don't need a separate count because servers.size
contains that information.

def load_server_list
    servers = []
    File.open('serverlist.txt').each do |line|
        next unless line =~ /^\S+$/
        next if line =~ /^#.*$/
        servers << line.chomp.sub(/\s+#.*$/, '')
    end
    servers
end

servers = load_server_list
p servers.size, servers




Sat, 09 Apr 2005 01:45:35 GMT  
 functional Ruby equiv to this perl snippet
Here's my attempt to squish that code down even further.

Quote:


> > # parses a text file looking for server names and ignoring lines
> > # with start with the pound/hash sign.

> It's pretty bad Perl, so here it is translated into pretty bad Ruby...

> def load_server_list
>     filename = "serverlist.txt"
>     file = open(filename, "r")
>     servers = []
>     while line = file.gets
>         line.chop!
>         next unless line =~ /\S/
>         next if line =~ /^#/
>         servers << line
>     end
>     file.close
>     return servers
> end

def load_server_list(file_name)
    servers = []
    IO.readlines(file_name).each { | line |
        # Next line assumes input always has newlines
        line = line.chomp!.strip                # chomp instead of chop
        next if line.empty? || line[0] == ?#    # Use ?# just to be different
        servers << line
    }
    return servers
end

servers = load_server_list(ARGV[0] || "serverlist.txt")
server_count = servers.length

Jim
--

"I invented the term Object-Oriented, and I can tell you I did not have C++
in mind." -- Alan Kay



Sat, 09 Apr 2005 02:24:23 GMT  
 functional Ruby equiv to this perl snippet

Quote:

> B> # parses a text file looking for server names and ignoring lines
> B> # with start with the pound/hash sign.

>  and ignoring empty lines, no ?

Yes!  : )


Sat, 09 Apr 2005 04:04:23 GMT  
 functional Ruby equiv to this perl snippet

<snip>
Quote:
> contains that information.

> def load_server_list
>     servers = []
>     File.open('serverlist.txt').each do |line|
>         next unless line =~ /^\S+$/
>         next if line =~ /^#.*$/
>         servers << line.chomp.sub(/\s+#.*$/, '')
>     end
>     servers
> end

> servers = load_server_list
> p servers.size, servers

Cool..but what if serverlist.txt does not exist? The one thing I do like
about Perl is the "open file or die" test. I believe that I am "stuck" with
a rescue clause which is sometimes confusing for me (a newbie) to use when
it is located within a "def".

Bob



Sat, 09 Apr 2005 04:35:07 GMT  
 functional Ruby equiv to this perl snippet

Quote:

>Cool..but what if serverlist.txt does not exist? The one thing I do like
>about Perl is the "open file or die" test. I believe that I am "stuck" with
>a rescue clause which is sometimes confusing for me (a newbie) to use when
>it is located within a "def".

You can do something very similar in Ruby, using "fail" instead of "die".
For example:

        def open_file name
          f = File.open(name) or fail "couldn't open #{name}"
          return f
        end

--Mirian



Sat, 09 Apr 2005 05:18:57 GMT  
 functional Ruby equiv to this perl snippet
Hi --

Quote:


> >Cool..but what if serverlist.txt does not exist? The one thing I do like
> >about Perl is the "open file or die" test. I believe that I am "stuck" with
> >a rescue clause which is sometimes confusing for me (a newbie) to use when
> >it is located within a "def".

> You can do something very similar in Ruby, using "fail" instead of "die".
> For example:

>    def open_file name
>      f = File.open(name) or fail "couldn't open #{name}"
>      return f
>         end

If an exception is raised by the open, though, the fail clause will
not be executed:

  $ ruby -e 'File.open("NO_FILE") or fail "Not reached"'
  -e:1:in `open': No such file or directory - "NO_FILE" (Errno::ENOENT)
          from -e:1

David

--
David Alan Black


Web:  http://pirate.shu.edu/~blackdav



Sat, 09 Apr 2005 05:33:11 GMT  
 functional Ruby equiv to this perl snippet

Quote:

> Cool..but what if serverlist.txt does not exist? The one thing I do
> like about Perl is the "open file or die" test. I believe that I am
> "stuck" with a rescue clause which is sometimes confusing for me (a
> newbie) to use when it is located within a "def".

Truth be told, you don't need to "or die". If you run the following
code (a minor modification to parameterize the filename), you'll get
(assuming, of course, that serverlist2.txt doesn't exist):

c:/home/Projects/Ruby/test.rb:4:in `initialize': No such file or
directory - "se
rverlist2.txt" (Errno::ENOENT)
        from c:/home/Projects/Ruby/test.rb:4:in `open'
        from c:/home/Projects/Ruby/test.rb:4:in `load_server_list'
        from c:/home/Projects/Ruby/test.rb:13

def load_server_list(filename)
    servers = []
    File.open(filename).each do |line|
        next unless line =~ /^\S+$/
        next if line =~ /^#.*$/
        servers << line.chomp.sub(/\s+#.*$/, '')
    end
    servers
end

servers = load_server_list('serverlist2.txt')
p servers.size, servers

To handle it as a caller, just replace the last two lines with
something like:

begin
    fn = 'serverlist2.txt'
    servers = load_server_list(fn)
rescue Errno::ENOENT => ex
    puts "Problem reading \"#{fn}\".\n\t#{ex.message}"
    exit
end

File.open automatically raises an error. Where you might want to do
something different is to have your own FileNotFoundException, like
so:

class FileNotFoundException < RuntimeError
end

def load_server_list(filename)
    servers = []
    File.exist?(filename) or raise FileNotFoundException, filename
    File.open(filename).each do |line|
        next unless line =~ /^\S+$/
        next if line =~ /^#.*$/
        servers << line.chomp.sub(/\s+#.*$/, '')
    end
    servers
end

begin
    servers = load_server_list('serverlist2.txt')
rescue FileNotFoundException => fnf
    puts "File '#{fnf.message}' does not exist."
    exit
end

If there is anywhere that I think that Ruby's class model is a bit
weak, it's in the existence of and documentation of 'standard'
exceptions. IMO, Errno::ENOENT is not what File.open should throw,
even though that's the actual errno value received -- it should throw
an appropriate readable exception (like FileNotFoundException) or
something like that.

-austin



Sat, 09 Apr 2005 05:33:22 GMT  
 functional Ruby equiv to this perl snippet

Quote:


> >Cool..but what if serverlist.txt does not exist? The one thing I do like
> >about Perl is the "open file or die" test. I believe that I am "stuck" with
> >a rescue clause which is sometimes confusing for me (a newbie) to use when
> >it is located within a "def".

> You can do something very similar in Ruby, using "fail" instead of "die".
> For example:

>         def open_file name
>           f = File.open(name) or fail "couldn't open #{name}"
>           return f
>         end

> --Mirian

Note that this isn't strictly necessary, unless you just want to provide your
own error message.  Ruby will die at that point anyway if the file doesn't
exist (and tell you why).  No need to test.

f = File.open("blah")
# Results in this:
# in `open': No such file or directory - "blah" (Errno::ENOENT)

Regards,

Dan



Sat, 09 Apr 2005 05:38:13 GMT  
 functional Ruby equiv to this perl snippet

<snip>
 >
Quote:
> > You can do something very similar in Ruby, using "fail" instead of
"die".
> > For example:

> >         def open_file name
> >           f = File.open(name) or fail "couldn't open #{name}"
> >           return f
> >         end

> > --Mirian

> Note that this isn't strictly necessary, unless you just want to provide
your
> own error message.  Ruby will die at that point anyway if the file doesn't
> exist (and tell you why).  No need to test.

> f = File.open("blah")
> # Results in this:
> # in `open': No such file or directory - "blah" (Errno::ENOENT)

> Regards,

> Dan

I would want to provide my own error message. I did not see the "fail"
option...grrrrr.


Sat, 09 Apr 2005 07:22:10 GMT  
 functional Ruby equiv to this perl snippet


<snip>

Quote:
> File.open automatically raises an error. Where you might want to do
> something different is to have your own FileNotFoundException, like
> so:

> class FileNotFoundException < RuntimeError
> end

> def load_server_list(filename)
>     servers = []
>     File.exist?(filename) or raise FileNotFoundException, filename
>     File.open(filename).each do |line|
>         next unless line =~ /^\S+$/
>         next if line =~ /^#.*$/
>         servers << line.chomp.sub(/\s+#.*$/, '')
>     end
>     servers
> end

> begin
>     servers = load_server_list('serverlist2.txt')
> rescue FileNotFoundException => fnf
>     puts "File '#{fnf.message}' does not exist."
>     exit
> end

I tried this one...replacing 'severlist2.txt' with my actual filename. I get
the following:

D:/Robert/Projects/Ruby/serverchk.rb/serverchk.rb:37:in `load_server_list':
wrong number of arguments(0 for 1) (ArgumentError)
        from D:/Robert/Projects/Ruby/serverchk.rb/serverchk.rb:37

Bob



Sat, 09 Apr 2005 07:38:38 GMT  
 
 [ 33 post ]  Go to page: [1] [2] [3]

 Relevant Pages 

1. Newbie: Ruby equiv for Perl while (<>)???

2. python equiv of perl's split?

3. Tcl equiv to perl localtime function

4. Tcl equiv to perl localtime function

5. Looking for tcl equiv. of perl pack/unpack

6. My Perl to Ruby Story (was: perl and rub y)

7. ruby equiv to python execfile?

8. Snippet request: Ruby Web Server written in under an hour

9. Ruby Code Snippet: Array.count

10. Perl => Ruby

11. Ruby advantages over Perl

12. Perl and Ruby: an Irony

 

 
Powered by phpBB® Forum Software