Home php教程 php手册 Split操作符

Split操作符

Jun 13, 2016 am 10:55 AM
split use Tabs string Split operate model blank

   Split它会根据给定的模式拆分字符串,对于使用制表符、冒号、空白符或任意符号分隔不同字段的字符串来说,用这个操作符分解提取字段相当方便。只要你能将分隔符写成模式(通常是很简单的正则表达式),就可以用Split分解数据。它的用法如下:

    my @fields = split /separator/, $string;

    这里的Split操作符用拆分模式扫描指定的字符串并返回字段(也就是子字符串)列表。期间只要模式在某处匹配成功,该处就是当前字段的结尾、下一字段的开头。所以,任何匹配模式的内容都不会出现在返回字段中。下面就是典型的以冒号作为分隔符的Split模式:

   my @fields = split /:/, “abc:def:g:h”;        #得到(“abc”,“def”,“g”,“h”)

    如果两个分隔符连在一起,就会产生空字段:

   my @fields = split /:/, “abc:def::g:h”;     #得到(“abc”,“def”,“”,“g”,“h”)

   这里有个规则,它乍看之下很古怪,但很少造成问题:Split会保留开头处的空字段,却舍去结尾处的空字段。例如:

   my @fields = split /:/, “:::a:b:c:::”;        #得到(“”,“”,“”,“a”,“b”,“c”)

    利用Split的/\s+/模式根据空白符分隔字符也是比较常见的做法。该模式把所有连续空白都视作单个空格并以此切分数据:

    my $some_input = “This  is a \t     test.\n”;

     my @args = split /\s+/, $some_input;     #得到(“This”,“is”,“a”,“test.”)

    默认Split会以空白符分隔$_中的字符串:

    my @fields = split;                       #等效于split /\s+/,$_;

    这几乎就等于以/\s+/为模式,只是它会省略开头的空字段。所以,即使该行以空白开头,你也不会在返回列表的开头处看到空字段。若你想以这种方式来分解用空格分隔的字符串,则可以用一个空格来作为模式:split ‘’, $other_string用一个空格来作为模式是split的特殊用法。

    一般来说,用在Split中的模式就像之前看到的这样简单。但如果你用到更复杂的模式,请避免在模式里使用捕获圆括号,因为这会启动所谓的“分隔符保留模式(详情请参见Perlfunc文档)。如果需要在模式中使用分组匹配,请在Split里使用非捕获圆括号(?:)的写法,以避免意外。

    进一步加深对Split分解提取字段带来的方便。下面给出一段我实际工作中未使用Split操作符分解提取字段的代码(后面还将给出使用Split操作符的代码)对比从中感受一下它的强大:

    任务:从passwd文件中提取用户名、用户主目录信息;

    我们先看一下passwd文件中记录格式(图1-1 部份摘录):

root:x:0:0:root:/root:/bin/bash

bin:x:1:1:bin:/bin:/bin/sh

……

    可以看出每个字段都用冒号(:)进行分隔,以第一条记录从左向右为例我们要提取第一个冒号前面的root(用户名)和第六个冒号前面的/root(用户主目录)。

[php]  

#代码1.1 未使用Split操作符提取字段代码;  

#!/usr/bin/perl -w  

use strict;  

open (FH, '/etc/passwd') or die "Can't open file: $!";  

while (){  

    my ($Pos,$endPos,$length,$Name,$Dir);  

    #############  

    # 取用户名称  

    #############  

    $length =  index ($_, ":");  

    $Name = substr ($_, 0, $length);  

    #####################  

    # 取用户HOME目录位置  

    #####################  

    $endPos = rindex ($_, ":");  

    # $endPos-1跳过当前位置(冒号)  

    $Pos = rindex ($_, ":", $endPos - 1);         

    # $Pos+1跳过当前位置(冒号)   

    # 查找方向从左向右。所以+1  

    $Pos += 1;  

    $length = $endPos - $Pos;  

    $Dir = substr ($_, $Pos, $length);  

          

    print "$Name\t$Dir\n";  

}  

close (FH);  

    程序运行后输出如下(图1-2):

root       /root

bin        /bin

……

    现在我们来分析一下这段代码的算法,提取用户名很简单只需要找到第一个冒号位置通过substr($_,0,$length)函数返回的子字符串即是需要的用户名。算法比较复杂的部份是提取用户主目录,通过图1-1可见passwd文件本身是有着固定格式的,记录从后向前(从右向左)倒数第二个冒号后面的/root就是用户主目录信息。

    提取用户主目录算法思想:

    1、  略过记录最后一个字段;

    2、  找到倒数第二个字段起始位置;

    3、  倒数第一个字段的起始(冒号)位置减去倒数第二个字段字符的开始位置(/号),得出来的结果就是用户主目录字段中的字符长度;

   4、  substr($_,$Pos,$length);返回用户主目录信息;

    5、完成。

 

    (图 1-3 提取用户目录算法)

    总结,通过Perl字符串处理函定位、提取字段信息可以完成我们的任务,可预见当我们要提取多个不相连字段,步骤将更繁琐,代码更长,也更加容易出错,如果,记录各字段位置发生改变,你将不得不重新设计你的算法。

    现在,我们再看使用Split操作符分解提取字段的例子:

[php]  

#代码1.2 使用Split操作符提取字段代码;  

#!/usr/bin/perl -w  

use strict;  

open (FH, '/etc/passwd') or die "Can't open file: $!";  

while (){  

  ###########  

  # 取用户信息  

  ###########     

  my($Name,$Dir) = (split /:/,$_)[0,5];  

                  

  print "$Name\t$Dir\n";  

}  

close (FH);  

 

  。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What software is crystaldiskmark? -How to use crystaldiskmark? What software is crystaldiskmark? -How to use crystaldiskmark? Mar 18, 2024 pm 02:58 PM

CrystalDiskMark is a small HDD benchmark tool for hard drives that quickly measures sequential and random read/write speeds. Next, let the editor introduce CrystalDiskMark to you and how to use crystaldiskmark~ 1. Introduction to CrystalDiskMark CrystalDiskMark is a widely used disk performance testing tool used to evaluate the read and write speed and performance of mechanical hard drives and solid-state drives (SSD). Random I/O performance. It is a free Windows application and provides a user-friendly interface and various test modes to evaluate different aspects of hard drive performance and is widely used in hardware reviews

How to download foobar2000? -How to use foobar2000 How to download foobar2000? -How to use foobar2000 Mar 18, 2024 am 10:58 AM

foobar2000 is a software that can listen to music resources at any time. It brings you all kinds of music with lossless sound quality. The enhanced version of the music player allows you to get a more comprehensive and comfortable music experience. Its design concept is to play the advanced audio on the computer The device is transplanted to mobile phones to provide a more convenient and efficient music playback experience. The interface design is simple, clear and easy to use. It adopts a minimalist design style without too many decorations and cumbersome operations to get started quickly. It also supports a variety of skins and Theme, personalize settings according to your own preferences, and create an exclusive music player that supports the playback of multiple audio formats. It also supports the audio gain function to adjust the volume according to your own hearing conditions to avoid hearing damage caused by excessive volume. Next, let me help you

How to use NetEase Mailbox Master How to use NetEase Mailbox Master Mar 27, 2024 pm 05:32 PM

NetEase Mailbox, as an email address widely used by Chinese netizens, has always won the trust of users with its stable and efficient services. NetEase Mailbox Master is an email software specially created for mobile phone users. It greatly simplifies the process of sending and receiving emails and makes our email processing more convenient. So how to use NetEase Mailbox Master, and what specific functions it has. Below, the editor of this site will give you a detailed introduction, hoping to help you! First, you can search and download the NetEase Mailbox Master app in the mobile app store. Search for "NetEase Mailbox Master" in App Store or Baidu Mobile Assistant, and then follow the prompts to install it. After the download and installation is completed, we open the NetEase email account and log in. The login interface is as shown below

How to use Baidu Netdisk app How to use Baidu Netdisk app Mar 27, 2024 pm 06:46 PM

Cloud storage has become an indispensable part of our daily life and work nowadays. As one of the leading cloud storage services in China, Baidu Netdisk has won the favor of a large number of users with its powerful storage functions, efficient transmission speed and convenient operation experience. And whether you want to back up important files, share information, watch videos online, or listen to music, Baidu Cloud Disk can meet your needs. However, many users may not understand the specific use method of Baidu Netdisk app, so this tutorial will introduce in detail how to use Baidu Netdisk app. Users who are still confused can follow this article to learn more. ! How to use Baidu Cloud Network Disk: 1. Installation First, when downloading and installing Baidu Cloud software, please select the custom installation option.

How to deal with blanks when playing PPT slides How to deal with blanks when playing PPT slides Mar 26, 2024 pm 07:51 PM

1. Open the PPT file you created and select the second slide. 2. On the second slide, select one of the pictures, and then select [Animation] to add any animation effect. 3. In the start column of the animation bar, change [While Standalone] to [After Previous Animation], and you will see that the picture animation label [1] will change to [0]. Do the same for subsequent slides, and you can see the effect by playing the slide at the end.

Do Not Disturb Mode Not Working in iPhone: Fix Do Not Disturb Mode Not Working in iPhone: Fix Apr 24, 2024 pm 04:50 PM

Even answering calls in Do Not Disturb mode can be a very annoying experience. As the name suggests, Do Not Disturb mode turns off all incoming call notifications and alerts from emails, messages, etc. You can follow these solution sets to fix it. Fix 1 – Enable Focus Mode Enable focus mode on your phone. Step 1 – Swipe down from the top to access Control Center. Step 2 – Next, enable “Focus Mode” on your phone. Focus Mode enables Do Not Disturb mode on your phone. It won't cause any incoming call alerts to appear on your phone. Fix 2 – Change Focus Mode Settings If there are some issues in the focus mode settings, you should fix them. Step 1 – Open your iPhone settings window. Step 2 – Next, turn on the Focus mode settings

BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? Apr 26, 2024 am 09:40 AM

MetaMask (also called Little Fox Wallet in Chinese) is a free and well-received encryption wallet software. Currently, BTCC supports binding to the MetaMask wallet. After binding, you can use the MetaMask wallet to quickly log in, store value, buy coins, etc., and you can also get 20 USDT trial bonus for the first time binding. In the BTCCMetaMask wallet tutorial, we will introduce in detail how to register and use MetaMask, and how to bind and use the Little Fox wallet in BTCC. What is MetaMask wallet? With over 30 million users, MetaMask Little Fox Wallet is one of the most popular cryptocurrency wallets today. It is free to use and can be installed on the network as an extension

How to use Xiaomi Auto app How to use Xiaomi Auto app Apr 01, 2024 pm 09:19 PM

Xiaomi car software provides remote car control functions, allowing users to remotely control the vehicle through mobile phones or computers, such as opening and closing the vehicle's doors and windows, starting the engine, controlling the vehicle's air conditioner and audio, etc. The following is the use and content of this software, let's learn about it together . Comprehensive list of Xiaomi Auto app functions and usage methods 1. The Xiaomi Auto app was launched on the Apple AppStore on March 25, and can now be downloaded from the app store on Android phones; Car purchase: Learn about the core highlights and technical parameters of Xiaomi Auto, and make an appointment for a test drive. Configure and order your Xiaomi car, and support online processing of car pickup to-do items. 3. Community: Understand Xiaomi Auto brand information, exchange car experience, and share wonderful car life; 4. Car control: The mobile phone is the remote control, remote control, real-time security, easy

See all articles