Saturday, 20 January 2018

بيرل الحركة من المتوسط - مثال


هذا الفصل يقدم لك المفاهيم وراء الإشارات إلى وحدات بيرل، والحزم، والطبقات. كما يظهر لك كيفية إنشاء عدد قليل من وحدات العينة. وحدة بيرل هي مجموعة من رموز بيرل التي تعمل مثل مكتبة المكالمات وظيفة. مصطلح الوحدة النمطية في بيرل مرادف لحزمة الكلمات. الحزم هي سمة من سمات بيرل 4، في حين وحدات سائدة في بيرل 5. يمكنك الحفاظ على كل ما تبذلونه من التعليمات البرمجية بيرل يمكن إعادة استخدامها محددة لمجموعة من المهام في وحدة بيرل. لذلك، يتم تضمين كافة الوظائف المتعلقة نوع واحد من المهمة في ملف واحد. أسهل لبناء تطبيق على هذه كتل وحدات. وبالتالي، فإن كلمة وحدة تطبيق أكثر قليلا من الحزمة. هيريس مقدمة سريعة للوحدات. سيتم تناول بعض المواضيع في هذا القسم بالتفصيل في بقية الكتاب. قراءة الفقرات التالية بعناية للحصول على لمحة عامة عن ما ينتظرنا في المستقبل عند الكتابة واستخدام الوحدات الخاصة بك. ما هو مربك هو أن المصطلحات وحدة وحزمة تستخدم بالتبادل في جميع وثائق بيرل، وهاتين المصطلحين يعني الشيء نفسه. حتى عند قراءة وثائق بيرل، مجرد التفكير كوتاكاجيكوت عندما ترى كوتمودولكوت والعكس بالعكس. لذلك، ما هي الفرضية لاستخدام وحدات حسنا، وحدات هناك لحزمة (العفو عن التورية) المتغيرات والرموز، وعناصر البيانات المترابطة معا. على سبيل المثال، باستخدام المتغيرات العالمية مع أسماء شائعة جدا مثل k. ي. أو i في برنامج عموما ليست فكرة جيدة. أيضا، عداد حلقة، ط. يجب أن يسمح للعمل بشكل مستقل في جزأين مختلفين من التعليمات البرمجية. سيؤدي الإعلان i كمتغير عام ومن ثم زيادته من داخل روتين فرعي إلى خلق مشاكل لا يمكن إدارتها مع رمز التطبيق الخاص بك لأنه قد تم استدعاء الروتين الفرعي من داخل حلقة يستخدم أيضا متغير يسمى i. استخدام وحدات في بيرل يسمح المتغيرات مع نفس الاسم ليتم إنشاؤها في أماكن مختلفة ومتميزة في نفس البرنامج. يتم تخزين الرموز المعرفة للمتغيرات الخاصة بك في مصفوفة ارتباطية، يشار إليها بجدول رموز. هذه الجداول رمز فريدة من نوعها لحزمة. لذلك، يمكن أن يكون للمتغيرات ذات الاسم نفسه في حزم مختلفة قيم مختلفة. كل وحدة لديها جدول الرموز الخاصة بها من جميع الرموز التي يتم الإعلان عنها. الجدول رمز يعزل أساسا الأسماء المترادفة في وحدة واحدة من آخر. يحدد جدول الرموز مساحة الاسم. أي مساحة لأسماء متغيرة مستقلة موجودة في. وهكذا، فإن استخدام وحدات، ولكل منها جدول الرموز الخاصة بها، يمنع متغير أعلن في قسم واحد من الكتابة فوق قيم المتغيرات الأخرى التي تحمل نفس الاسم المعلن في مكان آخر في نفس برنامج. في الواقع، جميع المتغيرات في بيرل تنتمي إلى حزمة. تنتمي المتغيرات في برنامج بيرل إلى الحزمة الرئيسية. جميع حزم أخرى ضمن برنامج بيرل إما متداخلة داخل هذه الحزمة الرئيسية أو موجودة في نفس المستوى. هناك بعض المتغيرات العالمية حقا، مثل مجموعة معالج الإشارات سيغ. التي تتوفر لجميع الوحدات النمطية الأخرى في برنامج تطبيق ولا يمكن عزلها عبر مساحات الاسم. يتم الاحتفاظ فقط تلك المعرفات المتغيرة التي تبدأ بحروف أو تسطير أسفل السطر في جدول رموز الوحدات النمطية. جميع الرموز الأخرى، مثل أسماء ستدين. ستدوت. ستدير. أرجف. أرغفوت. إنف. إنك. ويضطر سيغ إلى أن يكون في الحزمة الرئيسية. التبديل بين الحزم يؤثر على مساحات الأسماء فقط. كل ما تقوم به عند استخدام حزمة واحدة أو آخر هو الذي يحدد جدول الرموز لاستخدامها كجدول الرموز الافتراضي للبحث عن أسماء المتغيرات. تتأثر المتغيرات الديناميكية فقط باستخدام جداول الرموز. لا يزال يتم حل المتغيرات التي أعلن عنها استخدام الكلمة الرئيسية الخاصة بي مع كتلة التعليمات البرمجية التي تحدث في و يتم الإشارة إليها من خلال جداول الرموز. في الواقع، لا يزال نطاق إعلان حزمة نشطة فقط ضمن كتلة التعليمات البرمجية يتم الإعلان عنها في. لذلك، إذا قمت بتحويل الجداول رمز باستخدام حزمة ضمن روتين فرعي، سيتم استعادة الجدول رمز الأصلي في الواقع عند إجراء المكالمة عند عودة الروتين الفرعي. يؤدي تبديل جداول الرموز إلى التأثير فقط على البحث الافتراضي لأسماء المتغيرات الديناميكية. لا يزال بإمكانك الإشارة صراحة إلى المتغيرات، ومقابض الملفات، وهلم جرا في حزمة معينة عن طريق الإيداع المسبق ل باكاجينام. إلى اسم المتغير. رأيت ما هو سياق الحزمة عند استخدام المراجع في الفصل 3. سياق الحزمة يعني ببساطة استخدام جدول الرموز من قبل مترجم بيرل لحل الأسماء المتغيرة في البرنامج. عن طريق تبديل جداول الرموز، تقوم بتحويل سياق الحزمة. يمكن تداخل الوحدات النمطية ضمن وحدات أخرى. يمكن أن تستخدم الوحدة المتداخلة المتغيرات ووظائف الوحدة النمطية المتداخلة داخل. بالنسبة للوحدات المتداخلة، يجب استخدام مودولنام. نستدمودولنام وهلم جرا. استخدام القولون المزدوج (::) مرادف لاستخدام اقتباس العودة (). ومع ذلك، فإن القولون المزدوج هو الطريقة المفضلة والمستقبلية لمعالجة المتغيرات داخل الوحدات النمطية. تتم معالجة صريحة لمتغيرات الوحدة دائما مع مرجع كامل. على سبيل المثال، لنفترض أن لديك وحدة نمطية، الاستثمار. والتي هي الحزمة الافتراضية في الاستخدام، وتريد أن تعالج وحدة أخرى، السندات. والتي تتداخل ضمن وحدة الاستثمار. في هذه الحالة، لا يمكنك استخدام بوند ::. بدلا من ذلك، سيكون لديك لاستخدام الاستثمار :: بوند :: لمعالجة المتغيرات والوظائف داخل وحدة بوند. استخدام بوند :: يعني ضمنا استخدام حزمة السندات المتداخلة داخل الوحدة الرئيسية وليس ضمن وحدة الاستثمار. يتم تخزين الجدول رمز وحدة نمطية في الواقع في مصفوفة ربطية من أسماء الوحدات الملحقة مع اثنين من القولون. سيشار إلى جدول الرموز لوحدة نمطية تسمى بوند باسم المصفوفة النقابية بوند ::. اسم جدول الرموز للوحدة الرئيسية هو الرئيسي ::. ويمكن حتى تقصير إلى ::. وبالمثل، فإن جميع الحزم المتداخلة تحتوي على رموزها المخزنة في صفائف ارتباطية ذات نقطتين مزدوجتين تفصل كل مستوى من التداخل. على سبيل المثال، في وحدة بوند المتداخلة ضمن وحدة الاستثمار، سيتم تسمية الصفيف التراكمي للرموز في وحدة بوند إنفستمنت :: بوند ::. و تايبلدوب هو حقا نوع عالمي لاسم الرمز. يمكنك تنفيذ عمليات الاستعارة عن طريق تعيين إلى نوع تايبغلوب. سيتم استخدام إدخال واحد أو أكثر في مصفوفة ارتباطية للرموز عند استخدام تخصيص عن طريق تيبغلوب. القيمة الفعلية في كل إدخال مصفوفة ارتباطية هي ما تشير إليه عند استخدام التدوين فاريابلنام. وبالتالي، هناك طريقتان للإشارة إلى الأسماء المتغيرة في حزمة: الاستثمار :: المال الاستثمار :: الفواتير في الطريقة الأولى، كنت تشير إلى المتغيرات عبر مرجع تيدغلوب. استخدام الجدول رمز، الاستثمار ::. هو ضمني هنا، وسوف بيرل تحسين البحث عن رموز المال والفواتير. هذه هي الطريقة الأسرع والأفضل لمعالجة رمز. الطريقة الثانية تستخدم البحث عن قيمة المتغير الذي يتناوله المال والفواتير في الصفيف التراكمي المستخدم للرموز، الاستثمار :: صراحة. سيتم إجراء هذا البحث ديناميكيا ولن يكون الأمثل من قبل بيرل. لذلك، سيضطر البحث للتحقق من الصفيف التراكمي في كل مرة يتم تنفيذ البيان. ونتیجة لذلك، فإن الطریقة الثانیة لیست فعالة ولا ینبغي استخدامھا إلا لإثبات کیفیة تنفیذ جدول الرموز داخلیا. مثال آخر في هذا البيان كمران حسين يسبب المتغيرات، الروتين الفرعي، ومقابض الملفات التي تسمى عن طريق رمز كمران أيضا أن يعالج عن طريق رمز حسين. وهذا يعني أن كل إدخالات الرموز في جدول الرموز الحالي مع مفتاح كمران سوف تحتوي الآن على إشارات إلى تلك الرموز التي يعالجها المفتاح الرئيسي. لمنع مثل هذه المهمة العالمية، يمكنك استخدام مراجع صريحة. على سبيل المثال، فإن العبارة التالية تمكنك من معالجة محتويات حسين عبر متغير كمران. كمران حسين ومع ذلك، فإن أي صفائف مثل كمران و حسين لن تكون هي نفسها. ولن يتم تغيير سوى المراجع المحددة صراحة. لتلخيص، عند تعيين نوع واحد إلى آخر، تؤثر على كافة الإدخالات في جدول رموز بغض النظر عن نوع المتغير المشار إليه. عند تعيين مرجع من نوع متغير إلى آخر، تؤثر فقط إدخال واحد في جدول الرموز. يحتوي ملف وحدة بيرل على التنسيق التالي: باكيج مودولنام. إدراج رمز الوحدة النمطية. 1 يجب تسمية اسم الملف ModuleName. pm. يجب أن ينتهي اسم وحدة نمطية في سلسلة. pm حسب الاتفاقية. بيان العبوة هو السطر الأول من الملف. يجب أن يحتوي السطر الأخير من الملف على السطر مع العبارة 1. هذا في الواقع ترجع قيمة حقيقية لبرنامج التطبيق باستخدام وحدة نمطية. عدم استخدام عبارة 1 لن تسمح تحميل وحدة نمطية بشكل صحيح. بيان حزمة يخبر مترجم بيرل للبدء مع مجال مساحة اسم جديد. في الأساس، كل المتغيرات الخاصة بك في البرنامج النصي بيرل تنتمي إلى حزمة تسمى الرئيسية. ويمكن الإشارة إلى كل متغير في الحزمة الرئيسية على أنه متغير رئيسي. هيريس بناء الجملة لمثل هذه المراجع: باكاجناميفاريابلنام اقتباس واحد () مرادف لعامل القولون المزدوج (::). أغطى المزيد من الاستخدامات للمشغل :: في الفصل التالي. في الوقت الحالي، يجب أن نتذكر أن العبارات التالية ما يعادل: باكاجناميفاريابلنام باكاجينام :: فاريابلنام يعتبر بناء الجملة ثنائي القولون معيارا في عالم بيرل. لذلك، للحفاظ على القراءة، وأنا استخدم بنية القولون المزدوج في بقية هذا الكتاب إلا إذا كان من الضروري للغاية لجعل استثناءات لإثبات نقطة. الاستخدام الافتراضي لاسم متغير يحول إلى الحزمة الحالية النشطة في وقت التجميع. وهكذا، إذا كنت في حزمة Finance. pm وتحديد متغير بف. المتغير هو في الواقع يساوي المالية :: بف. استخدام وحدات بيرل: استخدام مقابل تتطلب تضمين وحدات بيرل في البرنامج باستخدام استخدام أو بيان تتطلب. هيريس طريقة استخدام أي من هذه العبارات: استخدام مودولنام تتطلب مودولنام لاحظ أن ملحق. pm لا يتم استخدامها في التعليمات البرمجية المبينة أعلاه. لاحظ أيضا أن كلا من البيانين لا يسمح بتضمين ملف أكثر من مرة في البرنامج. القيمة التي تم إرجاعها من ترو (1) كبيان آخر مطلوبة للسماح بيرل يعرف أن تتطلب d أو استخدام وحدة نمطية d تحميلها بشكل صحيح ويسمح المترجم بيرل تجاهل أي إعادة تحميل. بشكل عام، من الأفضل استخدام بيان وحدة الاستخدام من بيان وحدة تتطلب في برنامج بيرل لتبقى متوافقة مع الإصدارات المستقبلية من بيرل. بالنسبة للوحدات النمطية، قد ترغب في الاستمرار في استخدام عبارة الطلب. هيريس السبب: استخدام عبارة العمل أكثر قليلا من البيان المطلوب في أنه يغير مساحة اسم الوحدة النمطية التي تتضمن وحدة نمطية أخرى. تريد إجراء هذا التحديث الإضافي من مساحة الاسم في برنامج. ومع ذلك، عند كتابة التعليمات البرمجية لوحدة نمطية، قد لا تريد تغيير مساحة الاسم ما لم يطلب صراحة. في هذه الحالة، سوف تستخدم العبارة المطلوبة. يتضمن بيان المتطلبات اسم المسار الكامل لملف في مصفوفة إنك بحيث تكون الدالات والمتغيرات في ملف الوحدات النمطية في موقع معروف أثناء وقت التنفيذ. لذلك، يتم استيراد الدالات التي يتم استيرادها من وحدة نمطية عبر مرجع وحدة نمطية صريحة في وقت التشغيل مع عبارة الطلب. بيان الاستخدام يفعل نفس الشيء كما تتطلب العبارة لأنه يقوم بتحديث صفيف إنك مع أسماء المسارات كاملة من وحدات تحميلها. رمز وظيفة الاستخدام يذهب أيضا خطوة أبعد ويستدعي دالة الاستيراد في الوحدة التي يجري استخدامها د لتحميل بشكل صريح قائمة من الدوال المصدرة في وقت الترجمة، وبالتالي توفير الوقت المطلوب لحل صريح من اسم دالة أثناء التنفيذ. في الأساس، عبارة استخدام ما يعادل تتطلب مودولنام استيراد قائمة مودولنام من الدالات المستوردة استخدام عبارة الاستخدام لا تغيير مساحة اسم البرامج لأن أسماء الدالة المستوردة يتم إدراجها في جدول الرموز. لا يغير بيان المتطلبات مساحة اسم البرامج. لذلك، استخدام العبارة التالية مودولنام () ما يعادل هذا البيان: تتطلب مودولنام يتم استيراد الدالات من وحدة نمطية عبر استدعاء إلى دالة تسمى إيمبورت. يمكنك كتابة وظيفة الاستيراد الخاصة بك في وحدة نمطية، أو يمكنك استخدام وحدة المصدر واستخدام وظيفة الاستيراد. في جميع الحالات تقريبا، سوف تستخدم وحدة المصدر لتوفير وظيفة استيراد بدلا من إعادة اختراع العجلة. (عليك معرفة المزيد عن هذا في القسم التالي.) إذا قررت عدم استخدام وحدة المصدر، سيكون لديك لكتابة وظيفة الاستيراد الخاصة بك في كل وحدة التي تكتبها. أسهل بكثير لمجرد استخدام وحدة المصدر والسماح بيرل القيام بهذا العمل بالنسبة لك. نموذج رسالة. وحدة نمطية. أفضل طريقة لتوضيح دلالات كيفية استخدام وحدة نمطية في بيرل هو كتابة وحدة بسيطة وتظهر كيفية استخدامه. دعونا نأخذ مثال القرش القرض المحلي، روديوس مكسيموس، الذي هو ببساطة تعبت من كتابة نفس كوركستك ل بايمنتكوت الرسائل. كونه متعطشا مروحة من أجهزة الكمبيوتر و بيرل، روديوس يأخذ نهج المبرمجين كسول ويكتب وحدة بيرل لمساعدته على توليد مذكراته والحروف. الآن، بدلا من الكتابة داخل الحقول في ملف قالب مذكرة، كل ما عليه القيام به هو كتابة بضعة أسطر لإنتاج له لطيفة، مذكرة تهديد. قائمة 4.1 يظهر لك ما لديه لكتابة. قائمة 4.1. استخدام وحدة الرسالة. 1 أوسربينبرل - w 2 3 عدم إدخال الخط أدناه لتشمل دير الحالي في شركة 4 دفع (المؤتمر الوطني العراقي، بود) 5 6 استخدام رسالة 7 8 رسالة :: إلى (كوتمر المقامرة مانكوت، والمال ل لاكي الكلب، سباق 2 نقطة) 9 رسالة :: كليمونينيس () 10 رسالة :: ثانكسديم () 11 رسالة :: إنهاء () استخدام رسالة بيان موجود لإجبار مترجم بيرل لتشمل التعليمات البرمجية للوحدة في برنامج التطبيق. يجب أن تكون موجودة في وحدة في usrlibperl5 الدليل، أو يمكنك وضعه في أي دليل المدرجة في صفيف إنك. مصفوفة إنك هي قائمة الدلائل التي سوف يبحث عنها مترجم بيرل عند محاولة تحميل التعليمات البرمجية للوحدة النمطية المسماة. يظهر السطر المعلق (رقم 4) كيفية إضافة دليل العمل الحالي لتضمين المسار. الأسطر الأربعة التالية في الملف تولد الموضوع للرسالة. هيريس الإخراج من استخدام وحدة رسالة: إلى: السيد القمار رجل فم: روديوس مكسيموس، القرض القرش دت: ويد 7 فبراير 10:35:51 ست 1996 ري: المال لكوكي الكلب، سباق 2 لقد وصل إلى عنايتي أن حسابك قد تجاوز موعد استحقاقه. كنت ستعمل تدفع لنا قريبا أو هل تريد مني أن يأتي يوفا شكرا لدعمكم. يظهر ملف وحدة الرسالة في القائمة 4.2. ويعلن اسم الحزمة في السطر الأول. لأنه سيتم تصدير وظائف الوحدات النمطية هذه، استخدم وحدة المصدر. لذلك، استخدام البيان مطلوب المصدر لترث وظيفة من وحدة المصدر. هناك خطوة أخرى مطلوبة هي وضع الكلمة المصدرة في صفيف عيسى للسماح بالبحث عن Exported. pm. صفيف عيسى هو صفيف خاص داخل كل حزمة. يسرد كل عنصر في الصفيف مكان آخر للبحث عن أسلوب إذا تعذر العثور عليه في الحزمة الحالية. الترتيب الذي يتم إدراج الحزم في صفيف عيسى هو الترتيب الذي يبحث بيرل عن رموز لم يتم حلها. الفئة التي يتم سردها في صفيف عيسى يشار إلى الفئة الأساسية من فئة معينة. سوف بيرل ذاكرة التخزين المؤقت في عداد المفقودين الأساليب الموجودة في الطبقات الأساسية للمراجع في المستقبل. سيؤدي تعديل صفيف عيسى إلى مسح ذاكرة التخزين المؤقت وتسبب بيرل في البحث عن جميع الطرق مرة أخرى. دعونا ننظر الآن في التعليمات البرمجية ل letter. pm في القائمة 4.2. قائمة 4.2. وحدة ليتر. 1 حزمة 2 2 تتطلب مصدر 4 عيسى (المصدر) 5 6 head1 نيم 7 8 رسالة - نموذج وحدة لتوليد رأسية بالنسبة لك 9 10 head1 سينوسيس 11 12 استخدام رسالة 13 14 رسالة :: تاريخ () 15 رسالة :: إلى (الاسم ، الشركة، عنوان) 16 17 ثم واحد مما يلي: 18 رسالة :: كليمونينيس () 19 رسالة :: كليموني () 20 رسالة :: ثريتبرياكليغ () 21 22 رسالة :: ثانكديم () 23 رسالة :: إنهاء () 24 25 head1 دسكريبتيون 26 27 توفر هذه الوحدة نموذجا موجزا لتوليد رسالة ل 28 قرش قرض جاربود ودية. 29 30 تبدأ التعليمات البرمجية بعد بيان كوتكوت. 31 كت 32 33 إكسبورت كو (ديت، 34 تو، 35 كليموني، 36 كليمونونيس، 37 ثانكسدم، 38 فينيش) 39 40 41 طباعة تاريخ اليوم 42 43 سوب ليتر :: ديت 44 ديت ديت 45 طباعة اليوم اليوم هو ديتيكوت 46 47 48 فرعي ليتر :: إلى 49 تحويل محلي (الاسم) 50 تحول محلي (الموضوع) 51 طباعة إلى: الاسم 52 اقتباس الطباعة إف إم: روديوس مكسيموس، قرض شاركوت 53 طباعة كوتن ريت: سوبجيكتوت 55 برينت كوتنوت 56 برينت كوتنوت 57 58 سوب ليتر :: كليموني () 59 برينت كوتن كنت مدينون لي المال. الحصول على عملك سوميكوت 60 طباعة كوتن هل تريد مني أن أرسل برونو أكثر من كوت 61 الطباعة قصيدة جمعه. أو هل أنت ستعمل دفع أوكوت 62 63 64 سوب ليتر :: كليمونينيس () 65 برينت كوتن لقد وصلنا إلى عناية أن حسابك هو كوت 66 برينت كوتن أبوت المستحقة. كوت 67 برينت كوتن يو غونا أدف أوس ... كوت 68 طبعة منقوشة أو هل تريد مني أن يأتي أوفاهكوت 69 70 71 سوب ليتر :: ثريتبرياكليغ () 72 طباعة على ما يبدو حروف مثل هذه لا تساعد على طباعة 73 كوتن سوف تضطر إلى تقديم مثال على يوكوت 74 طباعة الاقتباس ن نراكم في المستشفى ، بالكوت 75 76 77 سوب ليتر :: ثانكدم () 78 برينت كوتن شكرا ل سوبورتكوت 79 80 81 رسالة فرعية :: فينيش () 82 برينتف كوتن سينسريليكوت 83 برينتف كوتن روديوس n كوت 84 85 86 1 خطوط محتوية على علامة المساواة للوثائق. يجب توثيق كل وحدة لوحدات بيرل المرجعية الخاصة بك لا تحتاج إلى أن تكون موثقة، ولكن من فكرة جيدة لكتابة بضعة أسطر حول ما تفعل التعليمات البرمجية الخاصة بك. بعد بضع سنوات من الآن، قد ننسى ما هو وحدة نمطية. التوثيق الجيد هو دائما لا بد منه إذا كنت تريد أن تتذكر ما فعلت في الماضي تغطية أنماط التوثيق المستخدمة ل بيرل في الفصل 8. كوتدوكومنتينغ بيرل سكريبتس. كوت لهذه الوحدة نموذج، يبدأ البيان head1 الوثائق. يتم تجاهل كل ما يصل إلى بيان قطع من قبل مترجم بيرل. بعد ذلك، يسرد الوحدة كافة الوظائف المصدرة بواسطة هذه الوحدة النمطية في صفيف التصدير. صفيف التصدير يعرف كل أسماء الدالات التي يمكن استدعاؤها بواسطة كود خارجي. إذا لم تقم بإدراج دالة في مجموعة التصدير هذه، فلن يتم مشاهدتها بواسطة وحدات كود خارجية. بعد صفيف التصدير هو الجسم من التعليمات البرمجية، روتين فرعي واحد في وقت واحد. بعد تعريف كافة الفرعين الفرعيين، ينتهي البيان النهائي 1 ملف الوحدة النمطية. 1 يجب أن يكون آخر خط قابل للتنفيذ في الملف. دعونا ننظر إلى بعض الوظائف المحددة في هذه الوحدة. الدالة الأولى للنظر في هي وظيفة التاريخ بسيطة، خطوط 43 إلى 46، الذي يطبع التاريخ والوقت يونيكس الحالي. لا توجد معلمات لهذه الوظيفة، وأنه لا يعود أي شيء مفيد إلى المتصل. لاحظ استخدام بلدي قبل متغير التاريخ في السطر 44. يتم استخدام كلمتي الرئيسية للحد من نطاق المتغير إلى داخل الأقواس مجعد وظائف التاريخ. ويشار إلى الرمز بين الأقواس المجعد ككتلة. المتغيرات المعلنة داخل كتلة محدودة في نطاق إلى داخل الأقواس مجعد. في 49 و 50، اسم المتغيرات المحلية والموضوع مرئية لجميع الوظائف. يمكنك أيضا تعريف المتغيرات بالمؤهل المحلي. ويسمح استعمال محلي للمتغير بأن يكون في النطاق للكتلة الحالية وكذلك لكتل ​​أخرى من الكود تسمى من داخل هذه الفدرة. وبالتالي، فإن x المحلي المعلن ضمن كتلة واحدة مرئي لجميع الفدرات اللاحقة التي تسمى من داخل هذه الكتلة ويمكن الرجوع إليها. في نموذج التعليمات البرمجية التالي، يمكن الوصول إلى متغير اسم الدالات توتيلد ولكن ليس البيانات في إفون. 1 سوب ليتر :: توتيتد 2 المحلية (الاسم) التحول 3 بلدي (الهاتف) شيفت نموذج التعليمات البرمجية ل letter. pm أظهرت كيفية استخراج معلمة واحدة في وقت واحد. الروتين الفرعي إلى () يأخذ معلمتين لإعداد رأس المذكرة. استخدام الدالات داخل الوحدة النمطية ليس مختلفا عن استخدام وتعريف وحدات بيرل داخل ملف التعليمات البرمجية نفسه. يتم تمرير المعلمات بالرجوع ما لم يحدد خلاف ذلك. يتم توصيل المصفوفات المتعددة التي يتم تمريرها إلى روتين فرعي، إذا لم يتم إزالتها بشكل صريح باستخدام الشرطة المائلة العكسية. صفيف الإدخال في دالة هو دائما صفيف من القيم العددية. تعد قيم النجاح بالرجوع هي الطريقة المفضلة في بيرل لتمرير كمية كبيرة من البيانات في روتين فرعي. (انظر الفصل 3. كوتيرنسز. كوت) نموذج آخر نموذج: المالية يتم استخدام وحدة المالية، المبينة في القائمة 4.3، لتوفير حسابات بسيطة لقيم القرض. استخدام وحدة المالية هو واضح. تتم كتابة كافة الوظائف بنفس المعلمات، كما هو مبين في الصيغة الخاصة بالوظائف. دعونا ننظر في كيفية حساب القيمة المستقبلية للاستثمار. على سبيل المثال، إذا كنت تستثمر بعض الدولارات، بف. في السندات التي تقدم نسبة مئوية ثابتة، r. تطبق على فترات معروفة لفترات زمنية n، ما هي قيمة السندات في وقت انتهاء صلاحيتها في هذه الحالة، عليك أن تستخدم الصيغة التالية: فف بف (1r) n يتم الإعلان عن وظيفة للحصول على القيمة المستقبلية كما فوتشرفالو . ارجع إلى قائمة 4.3 لمعرفة كيفية استخدامها. قائمة 4.3. استخدام وحدة المالية. 1 أوسربينبيرل - w 2 3 بوش (إنك، بود) 4 استخدام التمويل 5 6 قرض 5000.00 7 أبر 3.5 أبر 8 يار 10 إن يارس. 9 10 ------------------------------------------------ ---------------- 11 حساب القيمة في نهاية القرض إذا تم تطبيق الفائدة 12 كل عام. 13 ------------------------------------------------- --------------- 14 الوقت السنة 15 fv1 التمويل :: فوتيرفالو (القرض، أبر، الوقت) 16 الطباعة كوتن إذا تم تطبيق الفائدة في نهاية السنة 17 النشرة المطبوعة القيمة المستقبلية ل a قرض من كوت. قرض. كوتنوت 18 برينت كوت أت a أبر أوف كوت، أبر. كوت ل كوت، الوقت، كوت يارسكوت 19 برينتف هو 8.2f نكوت. fv1 20 21 ----------------------------------------------- ----------------- 22 حساب القيمة في نهاية القرض إذا تم تطبيق الفائدة 23 كل شهر. 24 ------------------------------------------------- --------------- 25 معدل أبر 12 أبر 26 الوقت 12 سنة بالأشهر 27 fv2 التمويل :: فوتوريفالو (القرض، معدل، الوقت) 28 29 طباعة المطبوعات إذا تم تطبيق الفائدة في نهاية كل مونثكوت 30 برينت كوتن القيمة المستقبلية للحصول على قرض من كوت. قرض. كوتنوت 31 برينت كوت أت a أبر أوف كوت، أبر. كوت ل كوت، الوقت، كوت مونثكوت 32 برينتف هو 8.2f نكوت. fv2 33 34 برينتف كوتن الفرق في القيمة هو 8.2fquot، fv2 - fv1 35 برينتف كوتن لذلك من خلال تطبيق الفائدة في فترات أقصر من الوقت 36 برينتف كوتن نحن في الواقع الحصول على المزيد من المال في الفائدة. نكوت هنا هو عينة المدخلات والمخرجات من قائمة 4.3. تيستم إذا تم تطبيق الفائدة في نهاية السنة القيمة المستقبلية للقرض 5000 دينار بمعدل فائدة سنوي قدره 3.5 سنوات لمدة 10 سنوات هي 7052.99 إذا تم تطبيق الفائدة في نهاية كل شهر القيمة المستقبلية للقرض 5000 بمعدل فائدة سنوي 3.5 120 شهر هو 7091.72 الفرق في القيمة هو 38.73 لذلك من خلال تطبيق الفائدة في فترات زمنية أقصر نحن في الواقع الحصول على المزيد من المال في الفائدة. الوحي في الإخراج هو نتيجة المقارنة بين القيم بين fv1 و fv2. يتم احتساب قيمة fv1 مع تطبيق الفائدة مرة واحدة كل عام على مدى عمر السند. fv2 هي القيمة إذا تم تطبيق الفائدة كل شهر بمعدل الفائدة الشهري المكافئ. يتم عرض حزمة Finance. pm في قائمة 4.4 في مراحل تطورها المبكرة. قائمة 4.4. حزمة Finance. pm. 1 حزمة التمويل 2 3 تتطلب مصدر 4 عيسى (المصدر) 5 6 head1 Finance. pm 7 8 حاسبة مالية - الحسابات المالية سهلة مع بيرل 9 10 رئيس 2 11 استخدام المالية 12 13 بف 10000.0 14 15 معدل 12.5 12 أبر شهريا. 16 17 الوقت 360 شهرا للحصول على قرض إلى ناضجة 18 19 فف فوتوريفالو () 20 21 طباعة فف 22 23 كت 24 25 إكسبورت كو (فوتوريفالو، 26 بريسنتفالو، 27 ففوفانيتي، 28 أنويتيوف، 29 جيتلاستافيراج، 30 جيتموفينغافيراج، 31 سيتينتيرست) 32 33 34 غلوبالز، إن وجدت 35 36 37 الافتراضي المحلي إنتيرست 5.0 38 39 سوب المالية :: سيتينتيريست () 40 بلدي معدل التحول () 41 ديفينتينتيريست ريت 42 برينتف كوتن ديفولتينريست ريتكيوت 43 44 45 -------------- -------------------------------------------------- ---- 46 ملاحظات: 47 1. يتم إعطاء سعر الفائدة r بقيمة 0-100. 48 2. n المعطى في الشروط هو المعدل الذي يتم تطبيق الفائدة 49. 50 51 ------------------------------------------------ -------------------- 52 53 ---------------------------- ---------------------------------------- 54 القيمة الحالية للاستثمار نظرا 55 فف - قيمة مستقبلية 56 r - معدل كل فترة 57 n - عدد الفترة 58 ---------------------------------- ---------------------------------- 59 سوب المالية :: فوتوريفالو () 60 بلدي (بف، ص، ن ) 61 فف بف ((1 (r100)) n) 62 عودة فف 63 64 65 ------------------------------ -------------------------------------- 66 القيمة الحالية للاستثمار نظرا 67 فف - مستقبل القيمة 68 r - المعدل لكل فترة 69 n - عدد الفترة 70 ------------------------------------ -------------------------------- 71 سوب المالية :: بريسنتفالو () 72 بلدي بف 73 بلدي (فف، ص، n) 74 بف فف ((1 (r100)) n) 75 ريتورن بف 76 77 78 79 ----------------------------- --------------------------------------- 80 الحصول على القيمة المستقبلية من المعاش نظرا 81 النائب - القسط الشهري للقسط 82 r - المعدل لكل فترة 83 n - العدد o f فترة 84 ----------------------------------------------- --------------------- 85 86 ففوفانويتي الفرعية () 87 بلدي فف 88 بلدي أونر 89 بلدي (مب، ص، ن) 90 91 أونر (1 ص) ن 92 فف مب ((أونر - 1) r) 93 ريتورن فف 94 95 96 --------------------------------- ----------------------------------- 97 الحصول على المعاش من البتات التالية من المعلومات 98 ص - معدل لكل الفترة 99 n - عدد الفترة 100 فف - القيمة المستقبلية 101 ------------------------------------- ------------------------------- 102 103 أنويتيوفف الفرعية () 104 بلدي النائب مب - الدفع الشهري من الأقساط 105 بلدي أونر 106 (فف، r، n) 107 108 أونر (1 r) n 109 مب فف (r (أونير - 1)) 110 ريتورن مب 111 112 113 ----------------- -------------------------------------------------- - 114 احصل على متوسط ​​آخر قيم كوتنوت في صفيف. 115 ------------------------------------------------- ------------------- 116 عدد آخر عدد من العناصر من المصفوفة في القيم 117 مجموع عدد العناصر في القيم في عدد 118 119 الفرعية جيتلاستافيراج () 120 بلدي (العدد، العدد، القيم) 121 I i 122 123 ماي a 0 124 ريتورن 0 إف (كونت 0) 125 فور (i 0 إيلت كونت i) 126 a فالويسنومبر - i - 127 127 128 إرجاع العد 129 130 131 --- -------------------------------------------------- --------------- 132 الحصول على المتوسط ​​المتحرك للقيم. 133 ------------------------------------------------- ------------------- 134 حجم النافذة هو المعلمة الأولى، وعدد العناصر في 135 مجموعة مرت هو التالي. (يمكن حساب ذلك بسهولة ضمن الدالة 136 باستخدام الدالة العددية ()، ولكن يتم استخدام الروتين الفرعي الموضح هنا 137 لتوضيح كيفية تمرير المؤشرات.) يتم تمرير المرجع إلى صفيف القيم 138 التالي، متبوعا ب بالإشارة إلى المكان 139 يتم تخزين قيم الإرجاع. 140 141 الفرعية جيتموفينغاف () 142 بلدي (العد، العدد، القيم، موفينغاف) 143 بلدي ط 144 بلدي a 0 145 بلدي v 0 146 147 عودة 0 إذا (العد 0) 148 عودة -1 إذا (عدد العد غ) 149 عودة - 2 إذا كان (لوت 2) 150 151 movAve0 0 152 موفينغافنومبر - 1 0 153 فور (i0 إيلتكونتي) 154 v فالسيسي 155 أف كونت 156 موفينغفي 0 157 158 فور (إكونت إلتنومبري) 159 v فاليميسي 160 أف كونت 161 v فالسيتي - كونت - 1 162 a - v كونت 163 موفينغافي a 164 165 ريتورن 0 166 167 168 1 أنظر إلى إعلان الوظيفة فوتوريفالو ب (). علامات الدولار الثلاث معا تشير إلى ثلاثة أرقام العددية التي تم تمريرها إلى وظيفة. هذا التحديد الإضافي موجود للتحقق من صحة نوع المعلمات التي تم تمريرها إلى الدالة. إذا كنت لتمرير سلسلة بدلا من رقم في الدالة، سوف تحصل على رسالة مشابهة جدا لهذا واحد: الكثير من الحجج المالية :: فوتوريفالو في. f4.pl خط 15 بالقرب من كوتيم) تنفيذ تنفيذ. f4.pl إحباط بسبب أخطاء التجميع. استخدام النماذج الأولية عند تحديد الوظائف يمنعك من إرسال قيم بخلاف ما تتوقعه الدالة. استخدام أو لتمرير في مجموعة من القيم. إذا كنت تمر بالرجوع، استخدم أو لإظهار مرجع عددي إلى صفيف أو تجزئة، على التوالي. إذا كنت لا تستخدم شرطة مائلة مائلة، يتم تجاهل جميع أنواع أخرى في النموذج قائمة الوسيطة. وتشمل الأنواع الأخرى من عوامل الاستبعاد علامة العطف للإشارة إلى الدالة، والنجمة لأي نوع، وفاصلة منقوطة للإشارة إلى أن جميع المعلمات الأخرى اختيارية. الآن، دعونا ننظر إلى إعلان وظيفة لاستموفينغايفيراج، الذي يحدد اثنين من الأعداد الصحيحة في الجبهة تليها مصفوفة. الطريقة التي يتم بها استخدام الوسيطات في الدالة هي تعيين قيمة لكل من العددين والعدد والرقمين. في حين يتم إرسال كل شيء آخر إلى الصفيف. نظرة على وظيفة جيتموفينغايفيغ () لنرى كيف يتم تمرير صفيفتين من أجل الحصول على المتوسط ​​المتحرك على قائمة القيم. يتم عرض طريقة استدعاء الدالة جيتموفينغايفيغ في قائمة 4.5. قائمة 4.5. استخدام وظيفة المتوسط ​​المتحرك. 1 أوسربينبرل - w 2 3 بوش (إنك، بود) 4 استخدام المالية 5 6 القيم (12،22،23،24،21،23،24،23،23،21،29،27،26،28) 7 مف ( 0) 8 الحجم العددية (القيم) 9 الطباعة القيمة القيم للعمل مع نكوت 10 طباعة كوت عدد القيم حجم نيكوت 11 12 ------------------------ ---------------------------------------- 13 حساب متوسط ​​الدالة أعلاه 14 - -------------------------------------------------- ------------- 15 أفي فينانس :: جيتلاستافراج (5، سيز، فالويس) 16 برينت كوتن متوسط ​​آخر 5 أيام أفي نيكوت 17 18 مالية :: جيتموفينغاف (5، سيز، فالويس، مف ) 19 الطباعة المنقولة المتوسط ​​المتحرك مع 5 أيام نافذة n نكوت هيريس الإخراج من قائمة 4.5: القيم للعمل مع عدد القيم 14 متوسط ​​آخر 5 أيام 26.2 تأخذ الدالة جيتموفينغايفيراج () اثنين من القياسات ثم مراجعتين إلى المصفوفات. وداخل الدالة، يتم إلغاء تحديد العددين المتحدين إلى المصفوفات لاستخدامهما كمصفوفات رقمية. يتم إدراج مجموعة القيم التي تم إرجاعها في المنطقة التي تم تمريرها كمرجع ثاني. إذا لم يتم تحديد معلمات الإدخال مع كل صفيف مرجعي، فإن مرجع صفيف موفينغيف كان سيكون فارغا وكان من شأنه أن يسبب أخطاء في وقت التشغيل. وبعبارة أخرى، فإن الإعلان التالي غير صحيح: سوب جيتموفينغاف () الناتج الناتج من رسائل الخطأ من نموذج وظيفة سيئة كما يلي: استخدام قيمة غير مهيأ في خط Finance. pm 128. استخدام قيمة غير مهيأ في خط Finance. pm 128. استخدام القيمة غير المهيأة في خط Finance. pm 128. استخدام القيمة غير المهيأة في خط المالية. pm 128. استخدام القيمة غير المهيأة على خط Finance. pm 128. استخدام القيمة غير المهيأة على خط Finance. pm 133. استخدام القيمة غير المهيأة في خط المالية 135. 135. استخدام القيمة غير المهيأة في خط Finance. pm 133. استخدام القيمة غير المهيأة في خط المالية. pm 135. استخدام القيمة غير المهيأة في خط المالية. pm 133. استخدام القيمة غير المهيأة في خط المالية 135.pm 135 استخدام القيمة غير المهيأة في خط Finance. pm 133. استخدام القيمة غير المهيأة في خط Finance. pm 135. استخدام القيمة غير المهيأة في خط Finance. pm 133. استخدام القيمة غير المهيأة في خط المالية. pm 135. استخدام القيمة غير المهيأة عند Finance. pm لين 133. استخدام القيم غير المهيأة e at Finance. pm line 135. Use of uninitialized value at Finance. pm line 133. Use of uninitialized value at Finance. pm line 135. Use of uninitialized value at Finance. pm line 133. Use of uninitialized value at Finance. pm line 135. Use of uninitialized value at Finance. pm line 133. Use of uninitialized value at Finance. pm line 135. Average of last 5 days 26.2 Moving Average with 5 days window This is obviously not the correct output. Therefore, its critical that you pass by reference when sending more than one array. Global variables for use within the package can also be declared. Look at the following segment of code from the Finance. pm module to see what the default value of the Interest variable would be if nothing was specified in the input. (The current module requires the interest to be passed in, but you can change this.) Heres a little snippet of code that can be added to the end of the program shown in Listing 4.5 to add the ability to set interest rates. 20 local defaultInterest 5.0 21 sub Finance::SetInterest() 22 my rate shift() 23 rate -1 if (rate lt 0) 24 defaultInterest rate 25 printf quotn defaultInterest ratequot 26 The local variable defaultInterest is declared in line 20. The subroutine SetInterest to modify the rate is declared in lines 21 through 26. The rate variable uses the values passed into the subroutine and simply assigns a positive value for it. You can always add more error checking if necessary. To access the defaultInterest variables value, you could define either a subroutine that returns the value or refer to the value directly with a call to the following in your application program: Finance::defaultInterest The variable holding the return value from the module function is declared as my variable . The scope of this variable is within the curly braces of the function only. When the called subroutine returns, the reference to my variable is returned. If the calling program uses this returned reference somewhere, the link counter on the variable is not zero therefore, the storage area containing the returned values is not freed to the memory pool. Thus, the function that declares my pv and then later returns the value of pv returns a reference to the value stored at that location. If the calling routine performs a call like this one: Finance::FVofAnnuity(monthly, rate, time) there is no variable specified here into which Perl stores the returned reference therefore, any returned value (or a list of values) is destroyed. Instead, the call with the returned value assigned to a local variable, such as this one: fv Finance::FVofAnnuity(monthly, rate, time) maintains the variable with the value. Consider the example shown in Listing 4.6, which manipulates values returned by functions. Listing 4.6. Sample usage of the my function. 1 usrbinperl - w 2 3 push(Inc, pwd) 4 use Finance 5 6 monthly 400 7 rate 0.2 i. e. 6 APR 8 time 36 in months 9 10 print quotn ------------------------------------------------quot 11 fv Finance::FVofAnnuity(monthly, rate, time) 12 printf quotn For a monthly 8.2f at a rate of 6.2f for d periodsquot, 13 monthly, rate, time 14 printf quotn you get a future value of 8.2f quot, fv 15 16 fv 1.1 allow 10 gain in the house value. 17 18 mo Finance::AnnuityOfFV(fv, rate, time) 19 20 printf quotn To get 10 percent more at the end, i. e. 8.2fquot, fv 21 printf quotn you need a monthly payment value of 8.2fquot, mo, fv 22 23 print quotn ------------------------------------------------ nquot Here is sample input and output for this function: testme ------------------------------------------------ For a monthly 400.00 at a rate of 0.20 for 36 periods you get a future value of 1415603.75 To get 10 percent more at the end, i. e. 1557164.12 you need a monthly payment value of 440.00 ------------------------------------------------ Modules implement classes in a Perl program that uses the object-oriented features of Perl. Included in object-oriented features is the concept of inheritance . (Youll learn more on the object-oriented features of Perl in Chapter 5. quotObject-Oriented Programming in Perl. quot) Inheritance means the process with which a module inherits the functions from its base classes. A module that is nested within another module inherits its parent modules functions. So inheritance in Perl is accomplished with the :: construct. Heres the basic syntax: SuperClass::NextSubClass. ThisClass. The file for these is stored in. SuperClassNextSubClass133 . Each double colon indicates a lower-level directory in which to look for the module. Each module, in turn, declares itself as a package with statements like the following: package SuperClass::NextSubClass package SuperClass::NextSubClass::EvenLower For example, say that you really want to create a Money class with two subclasses, Stocks and Finance . Heres how to structure the hierarchy, assuming you are in the usrlibperl5 directory: Create a Money directory under the usrlibperl5 directory. Copy the existing Finance. pm file into the Money subdirectory. Create the new Stocks. pm file in the Money subdirectory. Edit the Finance. pm file to use the line package Money::Finance instead of package Finance . Edit scripts to use Money::Finance as the subroutine prefix instead of Finance:: . Create a Money. pm file in the usrlibperl5 directory. The Perl script that gets the moving average for a series of numbers is presented in Listing 4.7. Listing 4.7. Using inheriting modules. 1 usrbinperl - w 2 aa pwd 3 aa . quotMoneyquot 4 push(Inc, aa) 5 use Money::Finance 6 values ( 12,22,23,24,21,23,24,23,23,21,29,27,26,28 ) 7 mv (0) 8 size scalar(values) 9 print quotn Values to work with nquot 10 print quot Number of values size nquot 11 ---------------------------------------------------------------- 12 Calculate the average of the above function 13 ---------------------------------------------------------------- 14 ave Money::Finance::getLastAverage(5,size, values) 15 print quotn Average of last 5 days ave nquot 16 Money::Finance::getMovingAve(5,size, values, mv) 17 foreach i (values) 18 print quotn Moving with 5 days window mvi nquot 19 20 print quotn Moving Average with 5 days window n nquot Lines 2 through 4 add the path to the Money subdirectory. The use statement in line 5 now addresses the Finance. pm file in the. Money subdirectory. The calls to the functions within Finance. pm are now called with the prefix Money::Finance:: instead of Finance:: . Therefore, a new subdirectory is shown via the :: symbol when Perl is searching for modules to load. The Money. pm file is not required. Even so, you should create a template for future use. Actually, the file would be required to put any special requirements for initialization that the entire hierarchy of modules uses. The code for initialization is placed in the BEGIN() function. The sample Money. pm file is shown in Listing 4.8. Listing 4.8. The superclass module for Finance. pm . 1 package Money 2 require Exporter 3 4 BEGIN 5 printf quotn Hello Zipping into existence for younquot 6 7 1 To see the line of output from the printf statement in line 5, you have to insert the following commands at the beginning of your Perl script: use Money use Money::Finance To use the functions in the Stocks. pm module, you use this line: use Money::Stocks The Stocks. pm file appears in the Money subdirectory and is defined in the same format as the Finance. pm file, with the exceptions that use Stocks is used instead of use Finance and the set of functions to export is different. A number of modules are included in the Perl distribution. Check the usrlibperl5lib directory for a complete listing after you install Perl. There are two kinds of modules you should know about and look for in your Perl 5 release, Pragmatic and Standard modules. Pragmatic modules, which are also like pragmas in C compiler directives, tend to affect the compilation of your program. They are similar in operation to the preprocessor elements of a C program. Pragmas are locally scoped so that they can be turned off with the no command. Thus, the command no POSIX turns off the POSIX features in the script. These features can be turned back on with the use statement. Standard modules bundled with the Perl package include several functioning packages of code for you to use. Refer to appendix B, quotPerl Module Archives, quot for a complete list of these standard modules. To find out all the. pm modules installed on your system, issue the following command. (If you get an error, add the usrlibperl5 directory to your path.) find usrlibperl5 - name perl quot. pmquot - print Extension modules are written in C (or a mixture of Perl and C) and are dynamically loaded into Perl if and when you need them. These types of modules for dynamic loading require support in the kernel. Solaris lets you use these modules. For a Linux machine, check the installation pages on how to upgrade to the ELF format binaries for your Linux kernel. The term CPAN (Comprehensive Perl Archive Network) refers to all the hosts containing copies of sets of data, documents, and Perl modules on the Net. To find out about the CPAN site nearest you, search on the keyword CPAN in search engines such as Yahoo. AltaVista, or Magellan. A good place to start is the metronet site . This chapter introduced you to Perl 5 modules and described what they have to offer. A more comprehensive list is found on the Internet via the addresses shown in the Web sites metronet and perl . A Perl package is a set of Perl code that looks like a library file. A Perl module is a package that is defined in a library file of the same name. A module is designed to be reusable. You can do some type checking with Perl function prototypes to see whether parameters are being passed correctly. A module has to export its functions with the EXPORT array and therefore requires the Exporter module. Modules are searched for in the directories listed in the Inc array. Obviously, there is a lot more to writing modules for Perl than what is shown in this chapter. The simple examples in this chapter show you how to get started with Perl modules. In the rest of the book I cover the modules and their features, so hang in there. I cover Perl objects, classes, and related concepts in Chapter 5.With weight vector I mean the vector with weights that you have to multiply the observations in the window that slides over your data with so if you add those products together it returns the value of the EMA on the right side of the window. بالنسبة إلى المتوسط ​​المتحرك المتوسط ​​المرجح، تكون الصيغة لإيجاد متجه الوزن: (1: n) سوم (1: n) (في الرمز R). This series of length n adds up to 1. For n10 it will be 0.01818182 0.03636364 0.05454545 0.07272727 0.09090909 0.10909091 0.12727273 0.14545455 0.16363636 0.18181818 the numbers 1 to 10 55, with 55 the sum of the numbers 1 to 10. How do you calculate the weight vector for an exponential moving average (EMA) of length n if n is the length of the window, then alphalt-2(n1) and ilt-1:n so EmaWeightVectorlt-((alpha(1-alpha)(1-i))) Is this correct Even though the EMA is not really confined to a window with a start and an end, shouldnt the weights add up to 1 just like with the LWMA Thanks Jason, any pointers of how to approximate the EMA filter to any desired precision by approximating it with a long-enough FIR filter There39s a perl script on en. wikipedia. orgwikihellip that made the image of the EMA weight vector, but I don39t understand it: if they set the number of weights to 15 why are there 20 red bars instead of 15 ndash MisterH Dec 19 12 at 22:40The belief that a change will be eas y to do correctly makes it less likely that the change will be done correctly. An XP programmer writes a unit test to clarify his intentions before he makes a change. We call this test-driven design (TDD) or test-first programming . because an API39s design and implementation are guided by its test cases. The programmer writes the test the way he wants the API to work, and he implements the API to fulfill the expectations set out by the test. Test-driven design helps us invent testable and usable interfaces. In many ways, testability and usability are one in the same. If you can39t write a test for an API, it39ll probably be difficult to use, and vice-versa. Test-driven design gives feedback on usability before time is wasted on the implementation of an awkward API. As a bonus, the test documents how the API works, by example. All of the above are good things, and few would argue with them. One obvious concern is that test-driven design might slow down development. It does take time to write tests, but by writing the tests first, you gain insight into the implementation, which speeds development. Debugging the implementation is faster, too, thanks to immediate and reproducible feedback that only an automated test can provide. Perhaps the greatest time savings from unit testing comes a few months or years after you write the test, when you need to extend the API. The unit test not only provides you with reliable documentation for how the API works, but it also validates the assumptions that went into the design of the API. You can be fairly sure a change didn39t break anything if the change passes all the unit tests written before it. Changes that fiddle with fundamental API assumptions cause the costliest defects to debug. A comprehensive unit test suite is probably the most effective defense against such unwanted changes. This chapter introduces test-driven design through the implementation of an exponential moving average (EMA), a simple but useful mathematical function. This chapter also explains how to use the CPAN modules Test::More and Test::Exception . Unit Tests A unit test validates the programmer39s view of the application. This is quite different from an acceptance test, which is written from the customer39s perspective and tests end-user functionality, usually through the same interface that an ordinary user uses. In constrast, a unit test exercises an API, formally known as a unit. Usually, we test an entire Perl package with a single unit test. Perl has a strong tradition of unit testing, and virtually every CPAN module comes with one or more unit tests. There are also many test frameworks available from CPAN. This and subsequent chapters use Test::More . a popular and well documented test module.2 I also use Test::Exception to test deviance cases that result in calls to die .3 Test First, By Intention Test-driven design takes unit testing to the extreme. Before you write the code, you write a unit test. For example, here39s the first test case for the EMA (exponential moving average) module: This is the minimal Test::More test. You tell Test::More how many tests to expect, and you import the module with useok as the first test case. The BEGIN ensures the module39s prototypes and functions are available during compilation of the rest of the unit test. The next step is to run this test to make sure that it fails: At this stage, you might be thinking, Duh Of course, it fails. Test-driven design does involve lots of duhs in the beginning. The baby steps are important, because they help to put you in the mindset of writing a small test followed by just enough code to satisfy the test. If you have maintenance programming experience, you may already be familiar with this procedure. Maintenance programmers know they need a test to be sure that their change fixes what they think is broken. They write the test and run it before fixing anything to make sure they understand a failure and that their fix works. Test-driven design takes this practice to the extreme by clarifying your understanding of all changes before you make them. Now that we have clarified the need for a module called EMA (duh), we implement it: And, duh, the test passes: Yeeha Time to celebrate with a double cappuccino so we don39t fall asleep. That39s all there is to the test-driven design loop: write a test, see it fail, satisfy the test, and watch it pass. For brevity, the rest of the examples leave out the test execution steps and the concomitant duhs and yeehas. However, it39s important to remember to include these simple steps when test-first programming. If you don39t remember, your programming partner probably will.4 Exponential Moving Average Our hypothetical customer for this example would like to maintain a running average of closing stock prices for her website. An EMA is commonly used for this purpose, because it is an efficient way to compute a running average. You can see why if you look at the basic computation for an EMA: today39s price x weight yesterday39s average x (1 - weight) This algorithm produces a weighted average that favors recent history. The effect of a price on the average decays exponentially over time. It39s a simple function that only needs to maintain two values: yesterday39s average and the weight. Most other types of moving averages, require more data storage and more complex computations. The weight, commonly called alpha . is computed in terms of uniform time periods (days, in this example): 2 (number of days 1) For efficiency, alpha is usually computed once, and stored along with the current value of the average. I chose to use an object to hold these data and a single method to compute the average. Test Things That Might Break Since the first cut design calls for a stateful object, we need to instantiate it to use it. The next case tests object creation: I sometimes forget to return the instance ( self ) so the test calls ok to check that new returns some non-zero value. This case tests what I think might break. An alternative, more extensive test is: This case checks that new returns a blessed reference of class EMA . To me, this test is unnecessarily complex. If new returns something, it39s probably an instance. It39s reasonable to rely on the simpler case on that basis alone. Additionally, there will be other test cases that will use the instance, and those tests will fail if new doesn39t return an instance of class EMA . This point is subtle but important, because the size of a unit test suite matters. The larger and slower the suite, the less useful it will be. A slow unit test suite means programmers will hesitate before running all the tests, and there will be more checkins which break unit andor acceptance tests. Remember, programmers are lazy and impatient, and they don39t like being held back by their programming environment. When you test only what might break, your unit test suite will remain a lightweight and effective development tool. Please note that if you and your partner are new to test-driven design, it39s probably better to err on the side of caution and to test too much. With experience, you39ll learn which tests are redundant and which are especially helpful. There are no magic formulas here. Testing is an art that takes time to master. Satisfy The Test, Don39t Trick It Returning to our example, the implementation of new that satisfies this case is: This is the minimal code which satisfies the above test. length doesn39t need to be stored, and we don39t need to compute alpha. We39ll get to them when we need to. But wait, you say, wouldn39t the following code satisfy the test, too Yes, you can trick any test. However, it39s nice to treat programmers like grown-ups (even though we don39t always act that way). No one is going to watch over your shoulder to make sure you aren39t cheating your own test. The first implementation of new is the right amount of code, and the test is sufficient to help guide that implementation. The design calls for an object to hold state, and an object creation is what needed to be coded. Test Base Cases First What we39ve tested thus far are the base cases . that is, tests that validate the basic assumptions of the API. When we test basic assumptions first, we work our way towards the full complexity of the complete implementation, and it also makes the test more readable. Test-first design works best when the implementation grows along with the test cases. There are two base cases for the compute function. The first base case is that the initial value of the average is just the number itself. There39s also the case of inputting a value equal to the average, which should leave the average unchanged. These cases are coded as follows: The is function from Test::More lets us compare scalar values. Note the change to the instantiation test case that allows us to use the instance ( ema ) for subsequent cases. Reusing results of previous tests shortens the test, and makes it easier to understand. The implementation that satisfies these cases is: The initialization of alpha was added to new . because compute needs the value. new initializes the state of the object, and compute implements the EMA algorithm. self-gt is initially undef so that case can be detected. Even though the implementation looks finished, we aren39t done testing. The above code might be defective. Both compute test cases use the same value, and the test would pass even if, for example, self-gt and value were accidentally switched. We also need to test that the average changes when given different values. The test as it stands is too static, and it doesn39t serve as a good example of how an EMA works. Choose Self-Evident Data In a test-driven environment, programmers use the tests to learn how the API works. You may hear that XPers don39t like documentation. That39s not quite true. What we prefer is self-validating documentation in the form of tests. We take care to write tests that are readable and demonstrate how to use the API. One way to create readable tests is to pick good test data. However, we have a little bootstrapping problem: To pick good test data, we need valid values from the results of an EMA computation, but we need an EMA implementation to give us those values. One solution is to calculate the EMA values by hand. Or, we could use another EMA implementation to come up with the values. While either of these choices would work, a programmer reading the test cases would have to trust them or to recompute them to verify they are correct. Not to mention that we39d have to get the precision exactly right for our target platform. Use The Algorithm, Luke A better alternative is to work backwards through the algorithm to figure out some self-evident test data.5 To accomplish this, we treat the EMA algorithm as two equations by fixing some values. Our goal is to have integer values for the results so we avoid floating point precision issues. In addition, integer values make it easier for the programmer to follow what is going on. When we look at the equations, we see alpha is the most constrained value: today39s average today39s price x alpha yesterday39s average x (1 - alpha) alpha 2 (length 1) Therefore it makes sense to try and figure out a value of alpha that can produce integer results given integer prices. Starting with length 1, the values of alpha decrease as follows: 1, 23, 12, 25, 13, 27, and 14. The values 1, 12, and 25 are good candidates, because they can be represented exactly in binary floating point. 1 is a degenerate case, the average of a single value is always itself. 12 is not ideal, because alpha and 1 - alpha are identical, which creates a symmetry in the first equation: today39s average today39s price x 0.5 yesterday39s average x 0.5 We want asymmetric weights so that defects, such as swapping today39s price and yesterday39s average, will be detected. A length of 4 yields an alpha of 25 (0.4), and makes the equation asymmetric: today39s average today39s price x 0.4 yesterday39s average x 0.6 With alpha fixed at 0.4, we can pick prices that make today39s average an integer. Specifically, multiples of 5 work nicely. I like prices to go up, so I chose 10 for today39s price and 5 for yesterday39s average. (the initial price). This makes today39s average equal to 7, and our test becomes: Again, I revised the base cases to keep the test short. Any value in the base cases will work so we might as well save testing time through reuse. Our test and implementation are essentially complete. All paths through the code are tested, and EMA could be used in production if it is used properly. That is, EMA is complete if all we care about is conformant behavior. The implementation currently ignores what happens when new is given an invalid value for length . Although EMA is a small part of the application, it can have a great impact on quality. For example, if new is passed a length of -1, Perl throws a divide-by-zero exception when alpha is computed. For other invalid values for length . such as -2, new silently accepts the errant value, and compute faithfully produces non-sensical values (negative averages for positive prices). We can39t simply ignore these cases. We need to make a decision about what to do when length is invalid. One approach would be to assume garbage-in garbage-out. If a caller supplies -2 for length . it39s the caller39s problem. Yet this isn39t what Perl39s divide function does, and it isn39t what happens, say, when you try to de-reference a scalar which is not a reference. The Perl interpreter calls die . and I39ve already mentioned in the Coding Style chapter that I prefer failing fast rather than waiting until the program can do some real damage. In our example, the customer39s web site would display an invalid moving average, and one her customers might make an incorrect investment decision based on this information. That would be bad. It is better for the web site to return a server error page than to display misleading and incorrect information. Nobody likes program crashes or server errors. Yet calling die is an efficient way to communicate semantic limits (couplings) within the application. The UI programmer, in our example, may not know that an EMA39s length must be a positive integer. He39ll find out when the application dies. He can then change the design of his code and the EMA class to make this limit visible to the end user. Fail fast is an important feedback mechanism. If we encounter an unexpected die . it tells us the application design needs to be improved. Deviance Testing In order to test for an API that fails fast, we need to be able to catch calls to die and then call ok to validate the call did indeed end in an exception. The function diesok in the module Test::Exception does this for us. Since this is our last group of test cases in this chapter, here39s the entire unit test with the changeds for the new deviance cases highlighted: There are now 9 cases in the unit test. The first deviance case validates that length can39t be negative. We already know -1 will die with a divide-by-zero exception so -2 is a better choice. The zero case checks the boundary condition. The first valid length is 1. Lengths must be integers, and 2.5 or any other floating point number is not allowed. length has no explicit upper limit. Perl automatically converts integers to floating point numbers if they are too large. The test already checks that floating point numbers are not allowed so no explicit upper limit check is required. The implementation that satisfies this test follows: The only change is the addition of a call to die with an unless clause. This simple fail fast clause doesn39t complicate the code or slow down the API, and yet it prevents subtle errors by converting an assumption into an assertion. Only Test The New API One of the most difficult parts of testing is to know when to stop. Once you have been test-infected, you may want to keep on adding cases to be sure that the API is perfect. For example, a interesting test case would be to pass a NaN (Not a Number) to compute . but that39s not a test of EMA . The floating point implementation of Perl behaves in a particular way with respect to NaNs6. and Bivio::Math::EMA will conform to that behavior. Testing that NaNs are handled properly is a job for the Perl interpreter39s test suite. Every API relies on a tremendous amount of existing code. There isn39t enough time to test all the existing APIs and your new API as well. Just as an API should separate concerns so must a test. When testing a new API, your concern should be that API and no others. Solid Foundation In XP, we do the simplest thing that could possibly work so we can deliver business value as quickly as possible. Even as we write the test and implementation, we39re sure the code will change. When we encounter a new customer requirement, we refactor the code, if need be, to facilitate the additional function. This iterative process is called continuous design . which is the subject of the next chapter. It39s like renovating your house whenever your needs change. 7 A system or house needs a solid foundation in order to support continuous renovation. Unit tests are the foundation of an XP project. When designing continuously, we make sure the house doesn39t fall down by running unit tests to validate all the assumptions about an implementation. We also grow the foundation before adding new functions. Our test suite gives us the confidence to embrace change. Quality Software Management: Vol. 1 Systems Thinking . Gerald Weinberg, Dorset House, 1991, p. 236. Part of the Test-Simple distribution, available at search. cpan. orgsearchqueryTest-Simple I used version 0.47 for this book. Just a friendly reminder to program in pairs, especially when trying something new. Thanks to Ion Yadigaroglu for teaching me this technique. In some implementations, use of NaNs will cause a run-time error. In others, they will cause all subsequent results to be a NaN. Don39t let the thought of continuous house renovation scare you off. Programmers are much quieter and less messy than construction workers.

No comments:

Post a Comment