投稿

2月, 2013の投稿を表示しています

javascript 自己ファイルへのSRC URLクエリから 引数

Quick Edit Pencil

// 引数確認 //
var debug = 1;
var br = "<br />";
var o = document.getElementsByTagName("script");
var d = o[o.length-1].src.substring(0, o[o.length-1].src.lastIndexOf("_userdata"));
debug ? document.write(d+br):0
if(o[o.length-1].src.match(/\?/i)){
var q = o[o.length-1].src.substring(o[o.length-1].src.lastIndexOf("?")+1);
debug ? document.write(q+br):0
function geturlqp(q,p){
if(q.match(RegExp(p+"=")))return q.replace(RegExp("(^.*?)("+p+")=(.*?)(&.*?$|$)"),"$3"); else return;
}
debug ? document.write(geturlqp(q,"mod")+br):0
debug ? document.write(geturlqp(q,"c")+br):0
}

javascript

Quick Edit Pencil

var br = "<br />";

//引数確認
var o = document.getElementsByTagName("script");

document.write(o);
document.write(br);

var s = o[o.length-1].src;

document.write(s);
document.write(br);

var d = o[o.length-1].src.substring(0, o[o.length-1].src.lastIndexOf("_userdata"));

document.write(d);
document.write(br);

if(s.match(/\?/i)){

var q = o[o.length-1].src.substring(o[o.length-1].src.lastIndexOf("?")+1);

document.write(q);
document.write(br);

var p = q.replace(/(^.*?)(c)=(.*?)(&.*?$|$)/,"$3");

document.write(p);
document.write(br);

function geturlqp(q,p){
return q.replace(RegExp("(^.*?)("+p+")=(.*?)(&.*?$|$)"),"$3");
}

document.write(geturlqp(q,"c"));
document.write(br);

document.write(geturlqp(q,"w"));

}

外部 javascript ファイルに SRCからURLクエリパラメーター(引数)を 渡す

Quick Edit Pencil

クライアント側(javascript) で<script>要素のsrc属性を解析する

ロード直後、自己の<script>要素のsrc属性から、URLクエリパラメータ(引数)を取得する

<HTML>
 <head>
  <script>
   src取得(../../script.js?c=book&w=dictionary)
    URLクエリパラメータ取得(c=book&w=dictionary)

// ../../script.js?c=book&w=dictionary

var o = document.getElementsByTagName("script");

var q = o[o.length-1].src.substring(o[o.length-1].src.lastIndexOf("?")+1); 

document.write(q); // c=book&w=dictionary

document.write(getUrlqp(q,"c")); // book

document.write(getUrlqp(q,"w")); // dictionary

function getUrlqp(q,p){
    return q.replace(RegExp("(^.*?)("+p+")=(.*?)(&.*?$|$)"),"$3");
}

perl 置換リスト 配列

Quick Edit Pencil

our @WORDS = (

[$triggerWord,''],

['^.*?id="layout-css|options-css|theme-css|page-css" />','<op> -d'],

['id="script-js"></script>','<op> -d -setStart -JS'],

['</script>','<op> -d -setEnd -JS'],

['id="bind-tag-cleaner-config-js">','<op> -d -setEnd'],

['</script>','<op> -d -setEnd -JS'],

['</script>','<op> -d -setEnd -JS']

);

第12回 2次元配列 - bingo_nakanishiの他言語出身者のためのPerl入門

se strict;
use Data::Dumper;

# 1次元配列
my @c = ('a', 'b', 'c');
my @d = ('e', 'f', 'g');
my @e = ('h', 'i', 'j', 'k', 'l');


# リファレンスで持たせるんだ!!!!
my @f = (
         \@c,
         \@d,
         \@e
        );

print Dumper \@f;

結果:

$VAR1 = [
          [
            'a',
            'b',
            'c'
          ],
          [
            'e',
            'f',
            'g'
          ],
          [
            'h',
            'i',
            'j',
            'k',
            'l'
          ]
        ];

javascript 外部ファイル パラメータ

Quick Edit Pencil

外部ファイルのスクリプトに引数を渡す方法 - JavaScriptプログラミング解説

// ※この関数は スクリプトの読み込み直後に呼ばれる必要がある
function GetScriptParams()
{
    var scripts = document.getElementsByTagName( 'script' );
    var src = scripts[ scripts.length - 1 ].src;

    var query = src.substring( src.indexOf( '?' ) + 1 );
    var parameters = query.split( '&' );

    // URLクエリを分解して取得する
    var result = new Object();
    for( var i = 0; i < parameters.length; i++ )
    {
        var element = parameters[ i ].split( '=' );

        var paramName = decodeURIComponent( element[ 0 ] );
        var paramValue = decodeURIComponent( element[ 1 ] );

        result[ paramName ] = decodeURIComponent( paramValue );
    }

    return result;
}
var configs = new Object; var scripts = document.getElementsByTagName("script"); for (var i = 0; i < scripts.length; i++) { var s = scripts[i]; if (s.src && s.src.match(/hoge\.js(\?.*)?/)) { var params = s.src.replace(/.+\?/, ''); break; } } params = params.split("&"); for(var i = 0; i < params.length; i++) { var tmp = params[i].split("="); configs[tmp[0]] = unescape(tmp[1]); }

var s = document.getElementsByTagName("script");
var d = s[s.length-1].src.match(/mode=p/);

Perl 何かのエラー?

Quick Edit Pencil

#-- 置換リスト検証 --#
# エラー:番号0060
if($after =~ m/-setEnd/ && $skipPair != $i){die print $PRINTHEADER . "! BiND Tag Cleaner CGI エラー 番号: 0060!".($i)."<br>複数行削除のペアリング異常<br>サイト管理者に連絡してください";}

onloadの代わりにDOMContentLoadedを使ってみる

Quick Edit Pencil

onloadの代わりにDOMContentLoadedを使ってみる - へぼいいいわけ

onloadイベントだとDOMの構築が完了しても画像を読み込み終わるまで待ってしまうので、代わりにDOMContentLoadedイベントを使って処理させてみます。IEにはDOMContentLoadedがないのでdocument.documentElement.doScroll("left")を監視してDOM構築が終わるまで再帰しています。

// DOM構築完了時の処理
function load(){
/*
なんかいろいろ
*/
};

// ユーザーエージェント
var userAgent = navigator.userAgent.toLowerCase();

// ページの構築が完了したらloadを呼び出す
(function(){
	if(document.addEventListener){ // opera,safari,mozilla向け
		document.addEventListener("DOMContentLoaded", load, false);
	} else if(/msie/.test(userAgent)){ // IE向け
		try {
			document.documentElement.doScroll("left");
		} catch(error){
			setTimeout(arguments.callee, 0);
			return;
		}
		load();
	} else { // その他
		window.onload = load;
	}
})();

javascript 環境変数

Quick Edit Pencil

JavaScriptで得られる環境変数 


■ navgator
   geolocation [object Geolocation]
   cookieEnabled true
   language ja-jp
   productSub 20030107
   product Gecko
   appCodeName Mozilla
   mimeTypes [object MimeTypeArray]
   vendorSub  
   vendor Apple Computer, Inc.
   platform MacIntel
   appName Netscape
   appVersion 5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/536.26.17 (KHTML, like Gecko) Version/6.0.2 Safari/536.26.17
   userAgent Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/536.26.17 (KHTML, like Gecko) Version/6.0.2 Safari/536.26.17
   plugins [object PluginArray]
   onLine true
   javaEnabled function javaEnabled() { [native code] }
   getStorageUpdates function getStorageUpdates() { [native code] }

 

■ document
   bgColor  
   alinkColor  
   width 1211
   plugins [object HTMLCollection]
   height 1068
   fgColor  
   vlinkColor  
   all [object HTMLAllCollection]
   embeds [object HTMLCollection]
   scripts [object HTMLCollection]
   compatMode BackCompat
   activeElement [object HTMLBodyElement]
   dir  
   designMode off
   linkColor  
   documentElement [object HTMLHtmlElement]
   preferredStylesheetSet null
   xmlVersion null
   webkitFullscreenElement null
   location http://www3.tokai.or.jp/tokotoko/memo/menu/js.html
   xmlEncoding null
   implementation [object DOMImplementation]
   webkitFullscreenEnabled true
   referrer http://www.google.co.jp/url?sa=t&rct=j&q=javascript%20%E7%92%B0%E5%A2%83%E5%A4%89%E6%95%B0&source=web&cd=8&sqi=2&ved=0CFsQFjAH&url=http%3A%2F%2Fwww3.tokai.or.jp%2Ftokotoko%2Fmemo%2Fmenu%2Fjs.html&ei=7cwnUb_NJM63kAW3hYHgDg&usg=AFQjCNEm5HDXZDtPyOLAz60qCqFartjsLg&bvm=bv.42768644,d.dGI
   webkitFullScreenKeyboardInputAllowed false
   head [object HTMLHeadElement]
   defaultView [object Window]
   domain www3.tokai.or.jp
   lastModified 05/14/2002 07:09:13
   anchors [object HTMLCollection]
   applets [object HTMLCollection]
   webkitCurrentFullScreenElement null
   doctype null
   images [object HTMLCollection]
   forms [object HTMLCollection]
   charset Shift_JIS
   styleSheets [object StyleSheetList]
   URL http://www3.tokai.or.jp/tokotoko/memo/menu/js.html
   readyState loading
   selectedStylesheetSet null
   characterSet Shift_JIS
   title JavaScript
   cookie  
   webkitIsFullScreen false
   body [object HTMLBodyElement]
   inputEncoding Shift_JIS
   xmlStandalone false
   documentURI http://www3.tokai.or.jp/tokotoko/memo/menu/js.html
   defaultCharset shift_jis
   links [object HTMLCollection]
   previousSibling null
   parentNode null
   lastChild [object HTMLHtmlElement]
   baseURI http://www3.tokai.or.jp/tokotoko/memo/menu/js.html
   firstChild [object HTMLHtmlElement]
   nodeValue null
   textContent null
   nodeType 9
   nodeName #document
   prefix null
   childNodes [object NodeList]
   nextSibling null
   attributes null
   ownerDocument null
   namespaceURI null
   localName null
   parentElement null
   write function write() { [native code] }
   hasFocus function hasFocus() { [native code] }
   captureEvents function captureEvents() { [native code] }
   writeln function writeln() { [native code] }
   close function close() { [native code] }
   clear function clear() { [native code] }
   releaseEvents function releaseEvents() { [native code] }
   open function open() { [native code] }
   evaluate function evaluate() { [native code] }
   createRange function createRange() { [native code] }
   webkitCancelFullScreen function webkitCancelFullScreen() { [native code] }
   createEvent function createEvent() { [native code] }
   getCSSCanvasContext function getCSSCanvasContext() { [native code] }
   createTextNode function createTextNode() { [native code] }
   createAttributeNS function createAttributeNS() { [native code] }
   createElement function createElement() { [native code] }
   importNode function importNode() { [native code] }
   createComment function createComment() { [native code] }
   caretRangeFromPoint function caretRangeFromPoint() { [native code] }
   createAttribute function createAttribute() { [native code] }
   queryCommandState function queryCommandState() { [native code] }
   getElementsByTagName function getElementsByTagName() { [native code] }
   createNodeIterator function createNodeIterator() { [native code] }
   querySelector function querySelector() { [native code] }
   createEntityReference function createEntityReference() { [native code] }
   getOverrideStyle function getOverrideStyle() { [native code] }
   createNSResolver function createNSResolver() { [native code] }
   adoptNode function adoptNode() { [native code] }
   queryCommandEnabled function queryCommandEnabled() { [native code] }
   getElementsByTagNameNS function getElementsByTagNameNS() { [native code] }
   getElementsByClassName function getElementsByClassName() { [native code] }
   createExpression function createExpression() { [native code] }
   createProcessingInstruction function createProcessingInstruction() { [native code] }
   createElementNS function createElementNS() { [native code] }
   createDocumentFragment function createDocumentFragment() { [native code] }
   createCDATASection function createCDATASection() { [native code] }
   queryCommandIndeterm function queryCommandIndeterm() { [native code] }
   queryCommandValue function queryCommandValue() { [native code] }
   getSelection function getSelection() { [native code] }
   getElementById function getElementById() { [native code] }
   createTreeWalker function createTreeWalker() { [native code] }
   execCommand function execCommand() { [native code] }
   queryCommandSupported function queryCommandSupported() { [native code] }
   getElementsByName function getElementsByName() { [native code] }
   elementFromPoint function elementFromPoint() { [native code] }
   querySelectorAll function querySelectorAll() { [native code] }
   webkitExitFullscreen function webkitExitFullscreen() { [native code] }
   hasAttributes function hasAttributes() { [native code] }
   NOTATION_NODE 12
   CDATA_SECTION_NODE 4
   contains function contains() { [native code] }
   isSupported function isSupported() { [native code] }
   ELEMENT_NODE 1
   DOCUMENT_POSITION_DISCONNECTED 1
   isEqualNode function isEqualNode() { [native code] }
   ENTITY_NODE 6
   TEXT_NODE 3
   ENTITY_REFERENCE_NODE 5
   DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC 32
   DOCUMENT_FRAGMENT_NODE 11
   cloneNode function cloneNode() { [native code] }
   dispatchEvent function dispatchEvent() { [native code] }
   PROCESSING_INSTRUCTION_NODE 7
   isDefaultNamespace function isDefaultNamespace() { [native code] }
   insertBefore function insertBefore() { [native code] }
   removeChild function removeChild() { [native code] }
   hasChildNodes function hasChildNodes() { [native code] }
   addEventListener function addEventListener() { [native code] }
   DOCUMENT_POSITION_PRECEDING 2
   normalize function normalize() { [native code] }
   compareDocumentPosition function compareDocumentPosition() { [native code] }
   DOCUMENT_TYPE_NODE 10
   COMMENT_NODE 8
   replaceChild function replaceChild() { [native code] }
   DOCUMENT_POSITION_FOLLOWING 4
   removeEventListener function removeEventListener() { [native code] }
   ATTRIBUTE_NODE 2
   DOCUMENT_POSITION_CONTAINED_BY 16
   DOCUMENT_NODE 9
   DOCUMENT_POSITION_CONTAINS 8
   appendChild function appendChild() { [native code] }
   isSameNode function isSameNode() { [native code] }
   lookupPrefix function lookupPrefix() { [native code] }
   lookupNamespaceURI function lookupNamespaceURI() { [native code] }

 

■ screen
   availTop 22
   width 1920
   availHeight 1178
   height 1200
   availWidth 1859
   availLeft 0
   colorDepth 24
   pixelDepth 24
   height 1200
   width 1920
   colorDepth 24
   bufferDepth undefined
   updateInterval undefined

 

■ document.links
   length 0
   item function item() { [native code] }
   namedItem function namedItem() { [native code] }

 

■ location
   origin http://www3.tokai.or.jp
   hash  
   href http://www3.tokai.or.jp/tokotoko/memo/menu/js.html
   pathname /tokotoko/memo/menu/js.html
   ancestorOrigins [object DOMStringList]
   hostname www3.tokai.or.jp
   protocol http:
   port  
   host www3.tokai.or.jp
   search  
   assign function assign() { [native code] }
   reload function reload() { [native code] }
   replace function replace() { [native code] }

 

■ history
   length 4
   state null
   back function back() { [native code] }
   replaceState function replaceState() { [native code] }
   pushState function pushState() { [native code] }
   go function go() { [native code] }
   forward function forward() { [native code] }



javascript dom 子要素リスト 要素数

Quick Edit Pencil

childNodesプロパティ(当該ノードの子ノードの配列) - DOMリファレンス

ある要素のオブジェクト e と兄弟関係になっている(同じ階層になっている)、href属性を持つ要素を探して処理する例です。

var e1=e.parentNode;
e1=e1.childNodes;
var i=-1;
while (++i<e1.length) {
    //  要素ノードでなければ弾く。
    if (e1[i].nodeType!=1) continue;
    //  href属性を持っていないなら弾く。
    if (e1[i].getAttribute('href')=='') contiune;

    (必要な処理)

    }

perl html エスケープ

Quick Edit Pencil

さぼてん: 【Perl】HTML エスケープとXSS対策

# HTML
my $html = qq|<script language="JavaScript">alert('にょろ');</script>\n|;

# 関数 xss()
print xss($html);

sub xss {
my $str = shift || return(undef);
$str =~ s/&/&amp;/g;
$str =~ s/</&lt;/g;
$str =~ s/>/&gt;/g;
$str =~ s/\"/&quot;/g;
$str =~ s/\'/&#39;/g; return($str);
}

javascript dom head 要素を削除

Quick Edit Pencil

DOM 要素の生成、削除 - JavaScript スタイルシートサンプル集

createElementメソッド

 新規に要素を生成するにはcreateElementメソッドの引数に
タグ名を指定し、属性名とその値を記述します。
 var Botan = document.createElement("input");
   Botan.type = "button";
   Botan.value = " ボタン";
   Botan.id = "BotanID";
     Botan.onclick =AddP;

上記のコードはつぎのHTMLタグを生成します。
<input type="button" value="ボタン" id="BotanID" onclick="AddP()"> 
変数 Botanはこれらを構成する要素ノードオブジェクトです。

appendChildメソッド

 生成した要素を任意の場所に表示します。
var Frm = document.getElementById("Myfrm");
   Frm.appendChild(Botan);
<body>内の表示したい場所に id属性を振ります。<div id="Myfrm"></div>
これでFrmの子要素として要素ノードオブジェクトBotanを追加表示します。

removeChildメソッド

引数に指定した要素ノードオブジェクトを削除します。
このメソッドは名前のように子要素を削除するメソッドですので
削除対象の要素の親要素が必要になります。
ここではparentNodeプロパティを使って,親要素を参照しています。
var Botan = document.getElementById("BotanID");
    Botan.parentNode.removeChild(Botan);

javascript DOM:ID名 クラス名を操作する。

Quick Edit Pencil

/*-------------------------------------------

BiNDスタイルを除去

-------------------------------------------*/

var removeBiNDstyles = [ 'layout-css', 'options-css', 'theme-css', 'page-css' ];

for (var i = 0; i < removeBiNDstyles.length; i ++) {

var Botan = document.getElementById(removeBiNDstyles[i]);

Botan.parentNode.removeChild(Botan);

}

 

/*-------------------------------------------

<body> id class 属性の追加

-------------------------------------------*/

window.onload = function(){

// クラスを追加

if(user_bodyclass){

add_class_name(document.getElementsByTagName('body')[0],user_bodyclass);}

//idを追加

if(user_bodyid){

add_id(document.getElementsByTagName('body')[0],user_bodyid);}

}

 

function add_class_name(obj,add_classes){

  var tmp_hash = new Array();

  var new_class_names = new Array();

  var class_names = obj.className.split(" ").concat(add_classes.split(" "));

  for(var i in class_names){if(class_names[i] != ""){tmp_hash[class_names[i]] = 0;}}

  for(var key in tmp_hash){new_class_names.push(key);}

  obj.className = new_class_names.join(" ");

}

 

function add_id(obj,add_id){

  var tmp_hash = new Array();

  var new_id_names = new Array();

  var id_names = obj.id.split(" ").concat(add_id.split(" "));

  for(var i in id_names){if(id_names[i] != ""){tmp_hash[id_names[i]] = 0;}}

  for(var key in tmp_hash){new_id_names.push(key);}

  obj.id = new_id_names.join(" ");

}

 

DOM:クラス名を操作する。

指定した要素のクラス名は「element.className」で取得・変更できる。
で、元々設定されているクラス名に追加、削除する関数を作ってみました。


追加 function add_class_name(obj,add_classes)

function add_class_name(obj,add_classes){
  var tmp_hash = new Array();
  var new_class_names = new Array();
  var class_names = obj.className.split(" ").concat(add_classes.split(" "));
  for(var i in class_names){if(class_names[i] != ""){tmp_hash[class_names[i]] = 0;}}
  for(var key in tmp_hash){new_class_names.push(key);}
  obj.className = new_class_names.join(" ");
}

削除 function delete_class_name(obj,delete_classes)

function delete_class_name(obj,delete_classes){
  var new_class_names = new Array();
  var class_names = obj.className.split(" ");
  var delete_class_names = delete_classes.split(" ");
  for(var i in class_names){
    var flag = true;
    for(var j in delete_class_names){
      if(class_names[i] == delete_class_names[j]){flag = false;break;};
    }
    if(flag){new_class_names.push(class_names[i])}
  }
  obj.className = new_class_names.join(" ");
}

JavaScriptメモ - DOM

DOMについてここにメモしていきます。

 「document.getElementById( ID )」でHTMLの要素につけたIDからその要素のオブジェクトを取得できます。

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ja">

<head>
<meta http-equiv="Content-Type" content="text/html; charset=shift_jis">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<title>DOMテスト</title>
</head>

<body>

<p id="targetElement">
 DOMの実験をします。このJavaScriptはこの段落の内容を取得します。
</p>

<p>
<a href="javascript:alert(document.getElementById('targetElement').innerHTML);">
段落の内容を取得
</a>
</p>

</body>
</html>

 「document.getElementsByName( Name )」でHTMLの要素につけた「Name」属性からその「Name」属性を持った要素のリストを取得できます。

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ja">

<head>
<meta http-equiv="Content-Type" content="text/html; charset=shift_jis">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<title>DOMテスト</title>
</head>

<body>

<p name="targetElement">
 DOMの実験をします。このJavaScriptはこの段落の内容を取得します。
</p>

<p>
<a href="javascript:alert(document.getElementsByName('targetElement')[0].innerHTML);">
段落の内容を取得
</a>
</p>

</body>
</html>

 「document.getElementsByTagName( タグ名 )」でHTMLのタグ名から要素のオブジェクトのリストを取得できます。

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ja">

<head>
<meta http-equiv="Content-Type" content="text/html; charset=shift_jis">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<title>DOMテスト</title>
</head>

<body>

<p>  DOMの実験をします。このJavaScriptはこの段落の内容を取得します。 </p>

<p>
<a href="javascript:alert(document.getElementsByTagName('p')[0].innerHTML);">
段落の内容を取得
</a>
</p>

</body>
</html>

 「createElement」と「appendChild」で要素を追加できます。「createTextNode」でテキストを追加し、「setAttribute」で属性を設定できます。

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ja">

<head>
<meta http-equiv="Content-Type" content="text/html; charset=shift_jis">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<meta http-equiv="Content-Style-Type" content="text/css">
<title>DOMテスト</title>
<script type="text/javascript">
<!--
function appendParagraph(){
 //段落のオブジェクトを生成
 var ParagraphObj = document.createElement('p');

 //ParagraphObj の子要素に 文字列のノード を追加
 ParagraphObj.appendChild(document.createTextNode('JavaScriptで追加した段落です'));

 //ParagraphObj の style を設定
 ParagraphObj.setAttribute('style', 'background-color:#E0E0E0;');

 //body の一番最後に追加
 document.body.appendChild(ParagraphObj);
}
-->
</script>
</head>

<body onload="appendParagraph()">

<p>
 DOMの実験をします。JavaScriptでDOMのノードを追加します。
</p>

</body>
</html>

 「document.body」以外でも、「getElementById」などで取得した要素にも「appendChild」で追加できます。

javascript 連想配列

Quick Edit Pencil

要素の削除

<script type="text/javascript">
var hash = { 'layout-css': 'head', 'options-css': 'head', 'theme-css': 'head', 'page-css': 'head', 'script-js': 'head' }
for (var key in hash) {
alert(key + ":" + hash[key] + "<br>");
Botan = document.getElementById(key);
Botan.parentNode.removeChild(Botan);
}</script>

perl 環境に依存しないで末尾の改行を削除

Quick Edit Pencil

chomp - 末尾の改行の削除 - サンプルコードによるPerl入門

# 環境に依存しないで末尾の改行を削除
$string =~ s/\x0D?\x0A?$//;

Perl 危険な関数

Quick Edit Pencil

4-2. Perl の危険な関数

perl 行内を文字検索

Quick Edit Pencil

Perlでテキストファイル内の検索文字列がある行数を求めるには - 燈明日記

◆サンプル

use strict;
use warnings;
use utf8;
binmode STDOUT, ':encoding(shiftjis)';

my $strText = << "END_OF_TEXT";
1234567890
ABCDEFGHIJ
1234567890
ABCDEFGHIJ
12小池啓仁AB
1234567890
ABCDEFGHIJ
END_OF_TEXT

my $linecnt;

if ($strText =~ /小池啓仁/) {
   $linecnt = scalar(() = ($` =~ /\n/g)) + 1;
   print "検索文字『小池啓仁』にヒットした行数:$linecnt\n";
}