---
title: "Perl中经常使用的一些方法"
author: "xmeteor"
date: "2013-01-05T17:32:54Z"
tags: []
categories: ["编程语言"]
slug: "perl"
draft: false
lastmod: "2013-01-06T14:36:53Z"
id: 1762790
url: "https://xmeteor.iteye.com/blog/1762790"
---

**<span style="color:red">检测操作系统的类型</span>**


```java
print "$^O\n";
```

linux on Linux and MSWin32 on Windows


```java
use English qw' -no_match_vars ';
print "$OSNAME\n";
```



```java
use Config;

print "$Config{osname}\n";
print "$Config{archname}\n";
```

<http://stackoverflow.com/questions/334686/how-can-i-detect-the-operating-system-in-perl>


**<span style="color:red">取得文件名称</span>**

```java
my $fileName = $file; # /tmp/test.log
$fileName =~ s!^.*(\\|\/)!!; # 得到fileName - "test.log"
```



**<span style="color:red">删除目录下的文件</span>**

```java
-d $_?rmtree($_):unlink $_ foreach (<data/*>);
```



**<span style="color:red">文件上传</span>**

```java
        if (!open(OUTFILE, ">$baseDir/$fileName")) {
            print "Cannot open the file $baseDir/$fileName";
            exit;
        }
        
        while (my $bytesRead = read($_, my $buffer, 1024)) {
            print OUTFILE $buffer;
        }
        close (OUTFILE);
```



<span style="color:red">**去掉字符串两边的空格或回车换行**</span>

```java
sub trim_str
{
    my $str = shift;

    if ($$str) {
      $$str =~ s/^\s+//g;
      $$str =~ s/\s+$//g;
      $$str =~ s/[\r\n]//g;
    }

    return $str;
}
```


**<span style="color:red">日期格式化</span>**

```java
use POSIX qw(strftime);
my $time = strftime("%Y%m%d%H%M%S", localtime(time));
```

<http://blog.chinaunix.net/uid-608135-id-2948410.html>