免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2497 | 回复: 9
打印 上一主题 下一主题

Code 优化: 10* lines to 1* lines? [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2010-02-05 20:04 |只看该作者 |倒序浏览
本帖最后由 ulmer 于 2010-02-05 20:09 编辑

Samba Configuration file: smb.conf
#
# Sample configuration file for the Samba suite for Debian GNU/Linux.
#
#
# This is the main Samba configuration file. You should read the
# smb.conf(5) manual page in order to understand the options listed
# here. Samba has a huge number of configurable options most of which
# are not shown in this example
#
# Any line which starts with a ; (semi-colon) or a # (hash)
# is a comment and is ignored. In this example we will use a #
# for commentary and a ; for parts of the config file that you
# may wish to enable
#
# NOTE: Whenever you modify this file you should run the command
# "testparm" to check that you have not many any basic syntactic
# errors.
#

#======================= Global Settings =======================

[global]

## Browsing/Identification ###

# Change this to the workgroup/NT-domain name your Samba server will part of
   workgroup = HOMENET

# server string is the equivalent of the NT Description field
   server string = %h server (Samba %v)

# Windows Internet Name Serving Support Section:
# WINS Support - Tells the NMBD component of Samba to enable its WINS Server
;   wins support = no

# WINS Server - Tells the NMBD components of Samba to be a WINS Client
# Note: Samba can be either a WINS Server, or a WINS Client, but NOT both
;   wins server = w.x.y.z

# This will prevent nmbd to search for NetBIOS names through DNS.
   dns proxy = no

# What naming service and in what order should we use to resolve host names
# to IP addresses
;   name resolve order = lmhosts host wins bcast


#### Debugging/Accounting ####

# This tells Samba to use a separate log file for each machine
# that connects
   log file = /var/log/samba/log.%m

# Put a capping on the size of the log files (in Kb).
   max log size = 1000

# If you want Samba to only log through syslog then set the following
# parameter to 'yes'.
;   syslog only = no

# We want Samba to log a minimum amount of information to syslog. Everything
# should go to /var/log/samba/log.{smbd,nmbd} instead. If you want to log
# through syslog you should set the following parameter to something higher.
   syslog = 0

# Do something sensible when Samba crashes: mail the admin a backtrace
   panic action = /usr/share/samba/panic-action %d


####### Authentication #######

# "security = user" is always a good idea. This will require a Unix account
# in this server for every user accessing the server. See
# /usr/share/doc/samba-doc/htmldocs/ServerType.html in the samba-doc
# package for details.
   security = user
   username map = /etc/samba/smbusers

# You may wish to use password encryption.  See the section on
# 'encrypt passwords' in the smb.conf(5) manpage before enabling.
   encrypt passwords = true

# If you are using encrypted passwords, Samba will need to know what
# password database type you are using.  
   passdb backend = tdbsam guest

   obey pam restrictions = yes

   guest account = nobody
   invalid users = root

# This boolean parameter controls whether Samba attempts to sync the Unix
# password with the SMB password when the encrypted SMB password in the
# passdb is changed.
;   unix password sync = no

# For Unix password sync to work on a Debian GNU/Linux system, the following
# parameters must be set (thanks to Augustin Luton <aluton@hybrigenics.fr> for
# sending the correct chat script for the passwd program in Debian Potato).
   passwd program = /usr/bin/passwd %u
   passwd chat = *Enter\snew\sUNIX\spassword:* %n\n *Retype\snew\sUNIX\spassword:* %n\n .

# This boolean controls whether PAM will be used for password changes
# when requested by an SMB client instead of the program listed in
# 'passwd program'. The default is 'no'.
;   pam password change = no


########## Printing ##########

# If you want to automatically load your printer list rather
# than setting them up individually then you'll need this
;   load printers = yes

# lpr(ng) printing. You may wish to override the location of the
# printcap file
;   printing = bsd
;   printcap name = /etc/printcap

# CUPS printing.  See also the cupsaddsmb(8) manpage in the
# cupsys-client package.
;   printing = cups
;   printcap name = cups

# When using [print$], root is implicitly a 'printer admin', but you can
# also give this right to other users to add drivers and set printer
# properties
;   printer admin = @ntadmin


######## File sharing ########

# Name mangling options
;   preserve case = yes
;   short preserve case = yes


############ Misc ############

# Using the following line enables you to customise your configuration
# on a per machine basis. The %m gets replaced with the netbios name
# of the machine that is connecting
;   include = /home/samba/etc/smb.conf.%m

# Most people will find that this option gives better performance.
# See smb.conf(5) and /usr/share/doc/samba-doc/htmldocs/speed.html
# for details
# You may want to add the following on a Linux system:
#         SO_RCVBUF=8192 SO_SNDBUF=8192
   socket options = TCP_NODELAY

# The following parameter is useful only if you have the linpopup package
# installed. The samba maintainer and the linpopup maintainer are
# working to ease installation and configuration of linpopup and samba.
;   message command = /bin/sh -c '/usr/bin/linpopup "%f" "%m" %s; rm %s' &

# Domain Master specifies Samba to be the Domain Master Browser. If this
# machine will be configured as a BDC (a secondary logon server), you
# must set this to 'no'; otherwise, the default behavior is recommended.
;   domain master = auto

# Some defaults for winbind (make sure you're not using the ranges
# for something else.)
;   idmap uid = 10000-20000
;   idmap gid = 10000-20000
;   template shell = /bin/bash

#======================= Share Definitions =======================

[homes]
   comment = Home Directories
   browseable = no

# By default, the home directories are exported read-only. Change next
# parameter to 'yes' if you want to be able to write to them.
;   writable = no
   writeable = yes

# File creation mask is set to 0700 for security reasons. If you want to
# create files with group=rw permissions, set next parameter to 0775.
   create mask = 0700

# Directory creation mask is set to 0700 for security reasons. If you want to
# create dirs. with group=rw permissions, set next parameter to 0775.
   directory mask = 0700

# Un-comment the following and create the netlogon directory for Domain Logons
# (you need to configure Samba to act as a domain controller too.)
;[netlogon]
;   comment = Network Logon Service
;   path = /home/samba/netlogon
;   guest ok = yes
;   writable = no
;   share modes = no

;[printers]
;   comment = All Printers
;   browseable = no
;   path = /tmp
;   printable = yes
;   public = no
;   writable = no
;   create mode = 0700

# Windows clients look for this share name as a source of downloadable
# printer drivers
;[print$]
;   comment = Printer Drivers
;   path = /var/lib/samba/printers
;   browseable = yes
;   read only = yes
;   guest ok = no
# Uncomment to allow remote administration of Windows print drivers.
# Replace 'ntadmin' with the name of the group your admin users are
# members of.
;   write list = root, @ntadmin

# A sample share for sharing your CD-ROM with others.
;[cdrom]
;   comment = Samba server's CD-ROM
;   writable = no
;   locking = no
;   path = /cdrom
;   public = yes

# The next two parameters show how to auto-mount a CD-ROM when the
#        cdrom share is accesed. For this to work /etc/fstab must contain
#        an entry like this:
#
#       /dev/scd0   /cdrom  iso9660 defaults,noauto,ro,user   0 0
#
# The CD-ROM gets unmounted automatically after the connection to the
#
# If you don't want to use auto-mounting/unmounting make sure the CD
#        is mounted on /cdrom
#
;   preexec = /bin/mount /cdrom
;   postexec = /bin/umount /cdrom

[public]
   comment = Public Folder
   path = /home/public
   guest ok = yes
   writeable = yes
   create mask = 0777
   directory mask = 0777
   force user = nobody
   force group = nogroup


Perl script to read smb.conf to display shared block(s):
shares.pl

  1. #!/usr/bin/perl -w

  2. use strict;

  3. sub usage()
  4.   {
  5.   print "\n\nProgram shares. Syntax:\n";
  6.   print "./shares conffile sharename  # prints out params for sharename\n";
  7.   print "./shares conffile            # prints out params for all shares\n";
  8.   print "Anything else prints out this message.\n\n";
  9.   }

  10. sub newShare(\%$)
  11.   {
  12.   %{$_[0]} = ("sharename"=>$_[1]);
  13.   }

  14. sub parseSmbDotConf($)
  15.   {
  16.   open(CONFIGFILE, "<" . $_[0]) || die "Cannot read file $_[0]\n";
  17.   my(@configMemoryImage) = <CONFIGFILE>;
  18.   close(CONFIGFILE);

  19.   my($state) = "init";
  20.   my(%allShares);

  21.   my(%share);
  22.   my($configLine);
  23.   foreach $configLine (@configMemoryImage)
  24.     {
  25.     if($configLine =~ /^\s*$/) {next;}; #Blow off blank lines
  26.     chomp($configLine);
  27.     $configLine =~ s/^\s+//;            #Delete leading blanks
  28.     $configLine =~ s/\s+$//;            #Delete trailing blanks
  29.     $configLine =~ s/;.*//;             #Delete comments
  30.     $configLine =~ s/#.*//;             #Delete comments
  31.     if($state eq "init")
  32.       {
  33.       newShare(%share, "GLOBAL");       #Leading params w/o share are [GLOBAL]
  34.       $state = "init2";
  35.       }

  36.     if($configLine =~ /^\s*\[\s*(.+)\s*\]\s*$/)        #if bracket line
  37.       {
  38.       if($state ne "init2")
  39.         {
  40.         ### RECORD PRIOR SHARE IN %allShares ###
  41.         $allShares{$share{"sharename"}} = {%share};
  42.         }
  43.       newShare(%share, uc($1));
  44.       $state = "brackets";
  45.       }
  46.     elsif($configLine =~ /^\s*(.+?)\s*=\s*(.+)\s*$/)    #if param line
  47.       {
  48.       my($key) = uc($1);
  49.       my($value) = $2;
  50.       $key =~ s/\s//g;
  51.       $share{$key} = $value;
  52.       $state = "param";
  53.       }
  54.     }
  55.   ### ADD FINAL SHARE TO %allShares ###
  56.   $allShares{$share{"sharename"}} = {%share};
  57.   return(%allShares);
  58.   }


  59. sub displayOneShare(\%$)
  60.   {
  61.   my(%allShares) = %{(shift)};
  62.   my($shareName) = shift;
  63.   my(%share) = %{$allShares{$shareName}};
  64.   my($key,$value);
  65.   print "\n\n********** [$shareName] **********\n";
  66.   foreach $key (sort(keys(%share)))
  67.     {
  68.     print "$key=" . $share{$key} . "\n";
  69.     }
  70.   }

  71. sub displayAll(\%)
  72.   {
  73.   my(%allShares) = %{(shift)};
  74.   my($key,$value);
  75.   foreach $key (sort(keys(%allShares)))
  76.     {
  77.     displayOneShare(%allShares, $key)
  78.     }
  79.   }

  80. sub main()
  81.   {
  82.   my(%shares);
  83.   if($#ARGV < 0)
  84.     {
  85.   usage();
  86.     }
  87.   else
  88.     {
  89.     %shares = parseSmbDotConf($ARGV[0]);
  90.     if($#ARGV == 0)
  91.       {
  92.       displayAll(%shares);
  93.       }
  94.     elsif($#ARGV == 1)
  95.       {
  96.       displayOneShare(%shares, uc($ARGV[1]));
  97.       }
  98.     else
  99.       {
  100.       usage();
  101.       }
  102.     }
  103.   }

  104. main();


复制代码


Above code is copy/past original source.
Who can write more simplified code?
Code Style => simple and short but more readable for normal user,
logical, user -interface friendly?

论坛徽章:
0
2 [报告]
发表于 2010-02-05 21:03 |只看该作者
写的可真乱。。。

这样的代码真是坏 perl 的名声啊

{:3_183:}

论坛徽章:
0
3 [报告]
发表于 2010-02-05 23:07 |只看该作者
缩进的格式有点乱。
推荐perltidy

论坛徽章:
1
狮子座
日期:2013-12-16 16:09:24
4 [报告]
发表于 2010-02-06 05:01 |只看该作者
  1. #!perl
  2. use strict;
  3. use warnings;
  4. {
  5.         my $vl_section='';
  6.         my $pl_userinput=qr/.*/;
  7.         defined $ARGV[1] and $pl_userinput=$ARGV[1];
  8.         open IN,$ARGV[0];
  9.         while (<IN>){
  10.                 /^\[(\w+)\]$/ and do {
  11.                         $vl_section=$1;
  12.                         $vl_section=~/^$pl_userinput$/ and print "******* [$vl_section] *******\n";
  13.                         next;
  14.                 };
  15.                 $vl_section=~/^$pl_userinput$/ && /^\s*([\w\s]+)\s*=\s*(.*)$/ and do {
  16.                         print uc($1)."=$2\n";
  17.                         next;
  18.                 };
  19.         }
  20.         close IN;
  21. }
复制代码
好难减到10* 良心上减不下去了

论坛徽章:
0
5 [报告]
发表于 2010-02-08 22:25 |只看该作者
本帖最后由 DQP 于 2010-02-08 22:51 编辑

  1. my $config_file = shift or die "missing conffile\n";
  2. open my $conf_fh, "<", $config_file;
  3. my $str = join "", grep { !m/^$/ } map { s/^\s*//; s/[#;].*$//; $_ } <$conf_fh>;
  4. my @sections = $str =~ m/\[(?<section>\w+)\]/mxg;
  5. @sections = shift if(@ARGV);
  6. for(@sections){
  7.     printf "********** [%s] **********\n", $_;
  8.     print $str =~ m/ \[(?:$_)\]\s*$ \s ((?:[\w\s]+\s*=\s*.+\s*$ \s)*) /mxg;
  9. }

复制代码

论坛徽章:
0
6 [报告]
发表于 2010-02-08 22:50 |只看该作者
本帖最后由 DQP 于 2010-02-08 22:56 编辑

  1. use Config::Std;
  2. my $config_file = shift || die "missing conffile\n";
  3. read_config $config_file => my %config;
  4. foreach my $section (shift || keys %config){
  5.     printf "\n\n********** [%s] **********\n", $section;
  6.     printf "%s=%s\n", $_, ${$config{$section}}{$_} for keys %{$config{$section}};
  7. }

复制代码

论坛徽章:
0
7 [报告]
发表于 2010-02-09 09:55 |只看该作者
这个code是传说中的gnu风格么?

论坛徽章:
0
8 [报告]
发表于 2010-02-09 10:11 |只看该作者
回复 7# redicaps


    好像还不是

论坛徽章:
1
狮子座
日期:2013-12-16 16:09:24
9 [报告]
发表于 2010-02-09 23:07 |只看该作者
果然是不短不perl啊

论坛徽章:
1
狮子座
日期:2013-12-16 16:09:24
10 [报告]
发表于 2010-02-09 23:21 |只看该作者
本帖最后由 ttcn_cu 于 2010-02-09 23:27 编辑
  1. my ($vl_section,$pl_userinput) = ( '' , defined $ARGV[1] ? join "|",@ARGV[1..$#ARGV] : qr/.*/);
  2. open IN,$ARGV[0] or die $!;
  3. while (<IN>){
  4.         /^\[(\w+)\]$/ && ($vl_section=$1) =~/^$pl_userinput$/ and print "******* [$vl_section] *******\n";
  5.         $vl_section=~/^$pl_userinput$/ && /^\s*([\w\s]+)\s*=\s*(.*)$/ and print $_;
  6. }
复制代码
再压缩一下
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP